Supporting Multiple HTTP Methods
Supporting Multiple HTTP Methods
Congratulations on making it to the final lesson of this course! So far, we've learned how to create individual endpoints using the HTTP methods: GET, POST, PUT, and DELETE in FastAPI. Now, it's time to integrate everything and create a FastAPI application that supports multiple HTTP methods.
Remember, each HTTP method serves a distinct purpose:
GETis used to retrieve data.POSTis used to add new data.PUTis used to update existing data.DELETEis used to remove data.
Let's put this knowledge into action and build our final application.
Setting up the FastAPI Application
First, let's set up our FastAPI application and establish the mock database we'll be utilizing:
This code block imports necessary modules, sets up the FastAPI application as app, and initializes a list crew serving as our mock database, which we'll be using throughout this lesson.
Async Endpoints
Recalling from our first unit, we understood how to create asynchronous endpoints. Let's recreate our GET method endpoint to read a specific crew member's details:
This code block defines an endpoint that responds to the GET HTTP method, accepting an integer crew_id as a path parameter. It then loops through the crew list to find and return the matched crew member. If no match is found, a message is returned indicating the crew member was not found.
POST Endpoint
Following that, we learned about the POST method for adding data. Just like we did before, we'll implement an endpoint to add a new crew member:
This endpoint handles the POST method and adds a new crew member to our list. The incoming request body is parsed for name and role data. A new ID is created, and then a new crew member is added with this ID. The details of the new crew member are then returned.
