Updating Items with PUT Requests

Updating Items with PUT Requests in FastAPI

Welcome back! We've explored GET and POST requests so far, and you've done a great job building endpoints using them. Now, we are going to learn another key HTTP method — PUT — which is primarily used for updating existing resources on the server. This lesson will guide you on how to build a PUT endpoint and effectively use it in your FastAPI application.

Setup Recap

Let's quickly revisit what we've learned in the previous lessons. We started our journey with FastAPI by understanding how to handle asynchronous HTTP requests and setting up a basic FastAPI application to manipulate a mock database.

Here's a snippet of the code we've been working with, which will serve as the foundation for our PUT endpoint:

from fastapi import FastAPI

app = FastAPI()

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

PUT Method In-Detail

A PUT request allows an API client to update an existing resource on the server, identified by the request URI. While PUT requests can also be used to create a new resource if it does not exist, this is not a requirement for the method.

For the sake of simplicity, in this lesson, we will focus solely on using the PUT method to update existing items. This operation is idempotent, meaning that no matter how many times you send the same request, the result will be the same each time.

For example, if you send a PUT request to update a crew member's role to "Engineer", sending the same request multiple times will not change the result after the first update—it will remain as "Engineer".

Constructing a PUT Endpoint

Setting up a PUT endpoint in FastAPI is similar to what you've done with GET and POST endpoints. This time, instead of @app.post, you'll use the decorator @app.put and specify the route. This decorator tells FastAPI that the function underneath is responsible for handling PUT requests received at the defined route.

Implementation Code

Take a look at the implementation code:

@app.put("/crew/{crew_id}")
async def update_crew_member(crew_id: int, request: Request):
    # Parse the incoming JSON request body
    data = await request.json()
    name = data["name"]
    role = data["role"]
    
    # Find crew member and update it
    for member in crew:
        if member["id"] == crew_id:
            member["name"] = name
            member["role"] = role
            return {"crew_id": crew_id, "crew_member": member}

    # If the crew member doesn't exist, return a not found message
    return {"message": "Crew member not found"}
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