Skip to main content
In this tutorial, you’ll learn how to configure SQLAlchemy to create tables in PostgreSQL and how to query data using both raw SQL and SQLAlchemy’s ORM within a FastAPI application. We will cover establishing a database connection, setting up models and dependencies, executing queries, and transitioning from raw SQL to ORM-based queries. ─────────────────────────────

Establishing the Database Connection

Begin by defining your data model and establishing a connection to PostgreSQL using psycopg2. The code snippet below demonstrates the basic setup for the model, connection loop, and sample posts:
─────────────────────────────

Setting Up FastAPI and SQLAlchemy

In your main application file, configure the FastAPI app alongside SQLAlchemy by setting up the database URL, engine, session, and dependency injection. Import your models and create all tables using Base.metadata.create_all(bind=engine). See the example below:
The database dependency function is defined in a separate module as follows:
─────────────────────────────

Querying the Database Using SQLAlchemy

FastAPI leverages dependency injection to perform database operations smoothly. Below are the examples of various endpoint routes:
  • The root endpoint simply returns a welcome message.
  • The /sqlalchemy endpoint uses SQLAlchemy’s ORM to fetch all posts.
  • The /posts endpoint demonstrates performing database queries using raw SQL with psycopg2.
  • The /posts POST route inserts a new post into the database.
Notice how the /sqlalchemy endpoint injects the db session to safely query the database without managing manual connections.
─────────────────────────────

Understanding Query Execution

SQLAlchemy delays executing a query until you explicitly request the results. Consider the following example:
Before calling .all(), the query object represents the SQL command internally. Invoking .all() triggers the complete SQL command to be generated and executed against your PostgreSQL database. ─────────────────────────────

Transitioning from Raw SQL to SQLAlchemy ORM

For a more maintainable and testable codebase, you can refactor your endpoints to utilize SQLAlchemy’s ORM. Updating your /posts route to use the dependency-injected session simplifies the operation:
Using the ORM approach reduces manual management of database connections and leverages dependency injection. This not only streamlines testing but also improves code maintainability.
─────────────────────────────

Testing and Verification

After updating your endpoints, perform the following steps to verify your implementation:
  1. Verify that the PostgreSQL database contains a single post by executing the following SQL command:
  2. Add a new post using the /posts endpoint. Then, make a new GET request to confirm that multiple posts are retrieved successfully.
The ORM approach encapsulates much of the SQL logic, allowing you to focus on building your FastAPI application while SQLAlchemy handles SQL generation behind the scenes. ─────────────────────────────

Conclusion

By following these steps, you have learned how to:
  • Establish a connection to PostgreSQL using psycopg2.
  • Set up FastAPI with SQLAlchemy dependencies.
  • Execute queries using both raw SQL and ORM-based methods.
  • Transition your code towards a more maintainable ORM approach.
In the next lesson, we will dive deeper into creating posts and performing additional CRUD operations with SQLAlchemy. Happy coding!

Watch Video