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