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:
GET
is used to retrieve data.POST
is used to add new data.PUT
is used to update existing data.DELETE
is used to remove data.
Let's put this knowledge into action and build our final application.
First, let's set up our FastAPI application and establish the mock database we'll be utilizing:
Python1from fastapi import FastAPI, Request 2 3app = FastAPI() 4 5# Mock database of crew members 6crew = [ 7 {"id": 1, "name": "Cosmo", "role": "Captain"}, 8 {"id": 2, "name": "Alice", "role": "Engineer"}, 9 {"id": 3, "name": "Bob", "role": "Scientist"} 10]
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.
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:
Python1@app.get("/crew/{crew_id}") 2async def read_crew_member(crew_id: int): 3 # Check if the crew member exists 4 for member in crew: 5 if member["id"] == crew_id: 6 return {"crew_id": crew_id, "crew_member": member} 7 # Return a message if not found 8 return {"message": "Crew member not found"}
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.
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:
Python1@app.post("/crew/") 2async def add_crew_member(request: Request): 3 # Parse the incoming request body 4 data = await request.json() 5 name = data["name"] 6 role = data["role"] 7 # Create a new ID and add crew member 8 crew_id = max(member["id"] for member in crew) + 1 if crew else 1 9 new_member = {"id": crew_id, "name": name, "role": role} 10 crew.append(new_member) 11 # Return new crew member details 12 return {"crew_id": crew_id, "crew_member": new_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.
Can you remember the third unit? We discussed the PUT
method for updating existing data. Let's recreate our endpoint for updating crew member details:
Python1@app.put("/crew/{crew_id}") 2async def update_crew_member(crew_id: int, request: Request): 3 # Parse the incoming request body 4 data = await request.json() 5 name = data["name"] 6 role = data["role"] 7 # Update the crew member's details in the mock database 8 for member in crew: 9 if member["id"] == crew_id: 10 member["name"] = name 11 member["role"] = role 12 return {"crew_id": crew_id, "crew_member": member} 13 # Return a message if not found 14 return {"message": "Crew member not found"}
In this code block, we define a PUT
endpoint. By parsing the incoming request body for updated name and role data, we can successfully update the existing member's details in our crew list. If the crew member doesn't exist, a message is returned.
Lastly, we learned about the DELETE
method for removing data. Here's how we developed the endpoint to delete a crew member:
Python1@app.delete("/crew/{crew_id}") 2async def delete_crew_member(crew_id: int): 3 # Remove the crew member from the mock database 4 for member in crew: 5 if member["id"] == crew_id: 6 crew.remove(member) 7 return {"message": "Crew member removed"} 8 # Return a message if not found 9 return {"message": "Crew member not found"}
This endpoint responds to the DELETE
method. It removes the crew member with the supplied crew_id
from our list. In case the crew member is not found, an appropriate message is returned.
In this lesson, our focus was to integrate our knowledge of various HTTP methods. We began by setting up a FastAPI application, then we reviewed each HTTP method, and created respective endpoints supporting each method in our application.
Learning is all about practice. It helps cement new knowledge and techniques and builds confidence. So, we have a set of exercises following this lesson. Give them a go!