Skip to main content
In this guide, we explain how to update a post resource by adding a new path operation that supports modifying posts. First, we introduce a basic update function that changes a post in an in-memory posts list.
Ensure that each code block is tested properly before deploying changes to production.

Basic Update Function

The following code shows a simple update function that finds a post by its ID and modifies it if it exists:

Updating the Database

Next, we update our database by grabbing the cursor object and executing an SQL query to update post attributes with the values provided by the user. To mitigate risk due to unpredictable user input, placeholders are used in the query for safely injecting data. Below is an updated code block that executes an SQL update query. Notice that the RETURNING clause in the SQL statement immediately returns the updated record:

Fetching the Updated Record

To retrieve the updated post, we need to call cursor.fetchone(). The following code snippet demonstrates this operation:
After the update, the query result is stored in a variable named updated_post. To ensure a successful update, we check if the result is None and return a 404 error if no post was updated.
At this point, our previous implementation becomes obsolete as we now rely on the updated record returned directly from the database query. If the update operation returns None, it indicates that no post with the given ID exists and a 404 error is triggered.

Finalizing the Update Endpoint

The final version of our update endpoint fetches the updated post directly using cursor.fetchone() and returns it. For example, if the database initially contains a post with ID 1 and you run:
You might see output similar to:
If you update the post with this JSON payload:
The endpoint should return:
After checking the database, you will find that the post has been updated correctly.
The initial update query did not include a WHERE clause, inadvertently updating every post. Always verify that your SQL queries update only the intended record.
To address this bug, add a WHERE condition to target the post with the specified ID. The updated SQL query is as follows:
After updating the post, running the following command:
will show that only the specified post is updated, though its position in the result set may change due to the modification. When testing with a non-existent post ID (for example, ID 23), the endpoint correctly returns a 404 error.

Final Update Endpoint Implementation

Below is the complete and corrected version of the update endpoint:
When testing, you might see log entries similar to:
Make sure that existing posts are updated as expected and that non-existent posts return the appropriate 404 error.

Additional Resources

Watch Video