Lesson 3
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:

Python
1from fastapi import FastAPI 2 3app = FastAPI() 4 5crew = [ 6 {"id": 1, "name": "Cosmo", "role": "Captain"}, 7 {"id": 2, "name": "Alice", "role": "Engineer"}, 8 {"id": 3, "name": "Bob", "role": "Scientist"} 9]
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:

Python
1@app.put("/crew/{crew_id}") 2async def update_crew_member(crew_id: int, request: Request): 3 # Parse the incoming JSON request body 4 data = await request.json() 5 name = data["name"] 6 role = data["role"] 7 8 # Find crew member and update it 9 for member in crew: 10 if member["id"] == crew_id: 11 member["name"] = name 12 member["role"] = role 13 return {"crew_id": crew_id, "crew_member": member} 14 15 # If the crew member doesn't exist, return a not found message 16 return {"message": "Crew member not found"}
Unpacking the Implementation

Let's understand the code step-by-step:

  1. The @app.put("/crew/{crew_id}") decorator defines the route and includes the crew member ID as a path parameter.
  2. The function update_crew_member accepts the path parameter crew_id and the request body containing the new name and role.
  3. The JSON data from the request body is extracted using await request.json().
  4. We loop through the crew list to find and update the crew member's details if the id matches the crew_id.
  5. If the crew member is found and updated, the updated data is returned; otherwise, a not found message is sent.
Why Use Path Parameters and Request Body?

In our PUT endpoint, we use both path parameters and the request body to achieve different purposes:

  • Path Parameters: These are used to uniquely identify the resource that needs to be updated. In our case, the crew_id path parameter helps locate the specific crew member in the list.
  • Request Body: This contains the actual data that will be updated. By sending the new name and role in the request body, we can make the necessary changes to the selected crew member's record.

Using path parameters and the request body together allows the API to clearly differentiate the resource being targeted from the data being used to perform the update. This results in a clean, intuitive, and efficient method for handling updates.

Wrapping Up and Gearing Up for Practice

Let's wrap up! Throughout this lesson, you've gained a deeper insight into the PUT HTTP method and how to use it in FastAPI for updating resources. You've come a long way and learned a lot — well done!

Remember, practice is key to understanding these concepts at a deeper level. Coming up next are some practice exercises that allow you to apply your newly acquired skills. Keep practicing, keep learning, and see you in the next lesson!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.