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 usingBase.metadata.create_all(bind=engine). See the example below:
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
/sqlalchemyendpoint uses SQLAlchemy’s ORM to fetch all posts. - The
/postsendpoint demonstrates performing database queries using raw SQL with psycopg2. - The
/postsPOST 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:.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:-
Verify that the PostgreSQL database contains a single post by executing the following SQL command:
-
Add a new post using the
/postsendpoint. Then, make a new GET request to confirm that multiple posts are retrieved successfully.
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.