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 theRETURNING clause in the SQL statement immediately returns the updated record:
Fetching the Updated Record
To retrieve the updated post, we need to callcursor.fetchone(). The following code snippet demonstrates this operation:
updated_post. To ensure a successful update, we check if the result is None and return a 404 error if no post was updated.
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 usingcursor.fetchone() and returns it. For example, if the database initially contains a post with ID 1 and you run:
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.