Removing Items with DELETE Requests

Removing Items with DELETE Requests in FastAPI

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.

FastAPI Recap

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:

from fastapi import FastAPI

app = FastAPI()

# Mock database of crew members
crew = [
    {"id": 1, "name": "Cosmo", "role": "Captain"},
    {"id": 2, "name": "Alice", "role": "Engineer"},
    {"id": 3, "name": "Bob", "role": "Scientist"}
]

Outcome Overview

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.

Building a DELETE Endpoint

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.

@app.delete("/crew/{crew_id}")
async def delete_crew_member(crew_id: int):
    # Find crew member and delete it
    for member in crew:
        if member["id"] == crew_id:
            crew.remove(member)
            return {"message": "Crew member removed"}

    # If the crew member doesn't exist, return a not found message
    return {"message": "Crew member not found"}

Understanding the Process

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal