What an amazing progress you did! So far, we have practiced making GET
, POST
, and PUT
requests, but there's more to HTTP methods. Let's start our discussion on the HTTP DELETE method.
Just like our previous lessons, every HTTP method has a unique role, and understanding when and why to use each one is a fundamental web development skill. As the name suggests, the DELETE
method is specifically used to remove a particular resource from the server.
Before we jump into exploring the DELETE
method, let's quickly look at how we set up our FastAPI
application and our mock directory of crew members, which we will be using again in this lesson:
Python1from fastapi import FastAPI 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]
Our task in this lesson is to create an endpoint using the DELETE
method to remove an item from our mock crew database. This deletion allows us to manage our data, keeping it consistent and updated, which is very important in real-world applications, such as updating the list of crew members on a spaceship after a member leaves.
Now, let's dive into the code and start building our DELETE
endpoint. To create a DELETE
endpoint, we simply need to change the decorator to @app.delete
and update what the function does to handle the deletion logic.
This endpoint will receive the crew_id
as a parameter from the URL, and that ID will be the identifier we will use to find and remove the crew member from the database.
Python1@app.delete("/crew/{crew_id}") 2async def delete_crew_member(crew_id: int): 3 # Find crew member and delete it 4 for member in crew: 5 if member["id"] == crew_id: 6 crew.remove(member) 7 return {"message": "Crew member removed"} 8 9 # If the crew member doesn't exist, return a not found message 10 return {"message": "Crew member not found"}
Let's walk through this process.
When you send a DELETE
request to /crew/{crew_id}
, the server looks for the crew member with that particular ID
. If it finds the crew member, it removes the member from our crew list and returns a success message, {"message": "Crew member removed"}
. However, if the specified crew member does not exist, it returns a not found message: {"message": "Crew member not found"}
.
Great job! You have now learned how to handle DELETE
requests with FastAPI
and built an endpoint to delete crew members from our mock database. This skill is important for maintaining accurate data in your applications.
In the forthcoming practice exercises, you will have the opportunity to consolidate this knowledge by creating your DELETE
endpoints. As we continue to explore FastAPI
, remember how different HTTP methods play a role in managing the data flow on our server.
We're proud of your progress and excited about your future creations. Keep going!