Skip to main content
In this article, we will explore how to query an individual post by its unique ID using SQLAlchemy. We transition from using raw SQL queries to leveraging SQLAlchemy’s ORM for improved abstraction, efficiency, and maintainability in database operations.

Creating a New Post

Below is an example that demonstrates creating a new post using the Post model and then returning it:

Legacy Raw SQL Endpoints

Previously, a GET endpoint for retrieving a single post was implemented using raw SQL as shown below:
Similarly, an endpoint to delete a post was defined as:

Migrating to SQLAlchemy

We will now replace these raw SQL operations with SQLAlchemy ORM queries. First, it is crucial to ensure that the database dependency is correctly injected into the function and that the post ID is passed as an integer.

Updated GET Endpoint with SQLAlchemy

Below is the modified GET endpoint using SQLAlchemy. Notice that the original raw SQL statements are retained as comments for reference:

Updating the Create Post Endpoint

In the creation endpoint, after showing the legacy raw SQL usage as a comment, we first commit the connection and then create a new post using the Post model:

Refining the SQLAlchemy Query for a Specific Post

When querying for a specific post, the goal is to mimic filtering by the post ID (i.e., the WHERE clause). Initially, the code was structured like this:
To clarify the process, we first assign the query result to a variable and print it for debugging:
After testing, you might encounter errors because the query is incomplete without evaluation. The correct approach is to fetch the first matching record using the .first() method:
After confirming that the query works correctly, remember to remove debugging print statements from your production code.

Sample Successful Response

After saving and testing these changes, a successful GET request for a post will return a JSON output similar to the following:
SQLAlchemy will also log the exact SQL query executed, resembling:

Error Handling Example

When trying to fetch a non-existent post (for example, with ID 666), the API returns a 404 error response:
Ensure that your error handling covers all edge cases to avoid exposing sensitive details about your database.
With these updates, the endpoint for fetching an individual post is now optimized, fully utilizing SQLAlchemy for database interactions, and is more maintainable for future improvements.

Watch Video