Skip to main content
In this article, we will demonstrate how to implement a DELETE path operation using SQLAlchemy and FastAPI. We start with executing a raw SQL DELETE command and gradually enhance our code by leveraging the SQLAlchemy ORM and dependency injection for managing database sessions.

Initial Implementation Using Raw SQL

Below is the initial approach where we directly execute an SQL DELETE command using a cursor. This method uses raw SQL to delete a post by its ID:

Enhancing with Dependency Injection

Next, we update the delete operation to use dependency injection for accessing the database session. In this version, we comment out the raw SQL commands and replace them with SQLAlchemy ORM logic:
Remember to commit the database session after deletion to persist the changes.

Verifying the Server Log

After running your server with the enhanced implementation, you should see logs similar to the following in your console:

Implementing a Helper Function for Post Retrieval

For better code organization, we create a helper function to retrieve a post by its ID. Instead of executing a raw SQL SELECT, we use the SQLAlchemy query:

Final Delete Endpoint Implementation

For our delete endpoint, we apply the same pattern: filtering posts by ID, checking for existence, and then performing the deletion using the ORM’s delete method. After deletion, the session is committed:
When the server is restarted with these changes, the console output may look like this:
Using dependency injection with SQLAlchemy ORM not only cleans up your code but also improves maintainability and testing.

Alternative Approach: Using SQLAlchemy Core

For scenarios where you might prefer SQLAlchemy Core, consider the following alternative. Although our example utilizes the ORM, this approach is both efficient and reliable:

Verifying the Deletion Operation

After successfully performing a deletion, verify the change through your PostgreSQL database. You can use this SQL command to list the remaining posts:
Test your delete endpoint using Postman. For example, sending a DELETE request for a non-existent post (e.g., with ID 4) should return a response like:
When deleting an existing post (for instance, the post with ID 6), the deletion should be successful. Running the SQL query again will confirm that the post has been removed.

Conclusion

This article illustrated the transition from a raw SQL approach to an ORM-based deletion strategy using FastAPI and SQLAlchemy. By leveraging dependency injection and the ORM’s robust query capabilities, you achieve a cleaner, more maintainable codebase. Happy coding!

Watch Video