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: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:.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: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.