Get startedGet started for free

PUT and DELETE operations

1. PUT and DELETE operations

Welcome back! We just built our first FastAPI endpoint to handle POST operations. Now, we will learn how to build endpoints to handle PUT and DELETE operations.

2. PUT vs. DELETE

First, let's learn how PUT and DELETE operations are used. Unlike POST operations that typically create objects, PUT and DELETE operations are traditionally used to update or delete existing objects. Like POST operations, they accept parameters from both the query string and the request body. Also like POST operations, they require an application or framework to send and receive requests.

3. Referencing Existing Objects

Referencing existing objects is the most important concept to understand when using PUT and DELETE operations. Frameworks with a built-in ORM handle this mapping for you automatically, but as we have learned, FastAPI does not have a built-in ORM. It is the application's responsibility to map API requests to objects it manages. This typically means mapping a parameter to the ID or other unique column of a database table. It's a common practice to include the name of the column in the parameter name. For example, we might name a parameter review_id to indicate that it is the ID column of the table called reviews, as we can see here in a pydantic model for DbReview that includes review_id as the last attribute. This same convention is used in many frameworks with a built-in ORM, so it is very familiar to API developers and users alike.

4. Handling a PUT Operation

Let's make a PUT endpoint to update an existing movie review. The endpoint is called "reviews." We use the @app.put annotation to tell FastAPI that this is a PUT operation. We follow it with a function `update_review` that defines the input and output types. Both are the pydantic model for DbReview objects that we defined in the previous slide, which includes the database identifier for the data to be updated. The function `update_review` updates the review data in a database and returns the same model.

5. Handling a DELETE Operation

Now, let's make a DELETE endpoint to delete an existing movie review. The endpoint is again called "reviews" and accepts the DbReview model as the request body. Recall that the DbReview model includes the database identifier for the data to be deleted. We use the @app.delete annotation to tell FastAPI that this is a DELETE operation. We follow it with a function delete_review, which deletes the review data from a database. The DELETE endpoint returns no data, since at the end of the operation the object is gone.

6. Let's practice!

Now, let's practice handling PUT and DELETE operations in FastAPI!

Create Your Free Account

or

By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.