FastAPI PUT and DELETE Requests
00:00 In this lesson, you’ll learn how to correct the number of sides in the dodecagon shape using your RestAPI, and you’ll also use the API to delete documents too. According to the REST standard, updates should be done using requests with the PUT HTTP method.
Just like with GET and POST, there’s a decorator for that. Since you want to update a specific document, the endpoint includes a
shape_id variable that identifies the document requiring the update. In addition, you’ll need to supply some data in the
@put body telling Mongita how to update the document. Therefore, the handler function for the PUT request will accept a
Shape model class.
The function signature looks like this. Inside of the
update_shape body, you should first check to see if a document with the ID exists. The
count_documents() method of the collection will return the number of documents meeting the criteria of a filter document. The filter document to find a document with a specific ID looks like this.
Instead of updating specific fields, for brevity you’ll replace the entire document with a new one. The result will be the same. The
.replace_one() method of the collection accepts the filter document, which again will look for documents with a specific ID and select the first.
01:52 There is another option for the update. Mongita supports the idea of an upsert. In other words, if an update is attempted for a document that does not exist, the replacement document will be created automatically.
Head back to the browser and refresh the documentation. Look for the PUT method to update the shape. Click the Try it out button and fill out the JSON, this time with the number of sides being
02:59 Click the Execute button and see the returned shape with the correct number of sides this time. Go to the GET method for all shapes, execute it, and see that the change has been committed and the database reflects the dodecagon with twelve sides.
.delete_one() method returns a delete result with a
deleted_count property. The
deleted_count is the number of documents removed, if any. Thus, if no document with the
shape_id exists, the
0 and no error is raised, so you could stop here and return a value indicating that there was no error.
Click the Execute button and see the status of the request is
200, and the returned JSON indicates the delete was completed. Go back to the GET method to list all shapes. Click the Try it out button. Click the Execute button.
Become a Member to join the conversation.