Skip to main content
In this guide, we will demonstrate how to update posts using SQLAlchemy in a FastAPI application. The update operation follows a familiar pattern similar to deleting or retrieving a post by its ID. We will cover how to query the database, validate that the post exists, perform the update, and return the updated result.

1. Original PostgreSQL-based Update (for reference)

Initially, a raw PostgreSQL update query might have been used:

2. Deleting a Post with SQLAlchemy

Before diving into the update, it is useful to review the deletion process using SQLAlchemy. This example ensures that database dependency configurations are set up correctly:

3. Update Operation Using SQLAlchemy

The update process with SQLAlchemy follows these steps:
  • Query the database for the post with the given ID.
  • Validate if the post exists.
  • Update the post using the values provided in the request.
  • Commit the changes and return the updated post.
Be sure to handle naming collisions between the input schema and the SQLAlchemy model instance. In our example, we use the name existing_post for the fetched instance.

Step 3.1: Preparing the Query and Validating the Post

Step 3.2: Updating the Post

You can either use hardcoded updated values or dynamically update with the incoming Pydantic model. Typically in production, you would use the provided data:

Step 3.3: Returning the Updated Post

After committing the update, re-query the database for the latest data to return:

4. Complete Updated Endpoint

Below is the final consolidated code for the update endpoint:

5. Testing the Update

To test the endpoint, send an update request with JSON data. For instance, using the following JSON payload:
The server logs might then reflect:
You can verify that the post has been updated in your database by running a query such as:

6. Important Considerations

  • Ensure that the dependency db: Session = Depends(get_db) is correctly configured in your application.
  • Avoid naming conflicts between the input schema (post) and the SQLAlchemy model instance by using a distinct variable name (e.g., existing_post).
  • Utilize the post.dict() method to convert the Pydantic model to a dictionary before applying the update with SQLAlchemy.
  • The synchronize_session=False flag is applied for performance optimization during updates.
Happy coding!

Watch Video