


Installing SQLAlchemy
First, install SQLAlchemy using pip:Keep in mind that SQLAlchemy does not communicate directly with a database; it requires a database driver (for instance,
psycopg2 for PostgreSQL or an equivalent driver for MySQL, SQLite, etc.). If you’re using PostgreSQL and have the driver installed, there is no need to reinstall it.Creating the Database Connection File
Create a file nameddatabase.py in your project. This file manages the database connection while setting up the SQLAlchemy engine, session, and base model. Below is a sample configuration. Note that for SQLite, you must include the connect_args parameter; for PostgreSQL or other databases, it is not necessary.
Defining Models
In an ORM, database tables are represented as Python classes. Create a file namedmodels.py to store your models. Each model corresponds to a table in your database. Below is an example model for a posts table demonstrating four columns: id, title, content, and published.
Initializing the Database in the Main Application
Within your main FastAPI application file (commonlymain.py), import your models and create the database tables. Additionally, set up a dependency to manage database sessions for API endpoints.
Below is an example implementation:
models.Base.metadata.create_all(bind=engine) to create the necessary database tables if they do not exist. The get_db function is a dependency that ensures every request gets its own session and that the session is properly closed afterward.
Testing the Database Connection
To verify that your database is properly connected, add a simple endpoint that queries the posts table. This example demonstrates the usage of the SQLAlchemy session dependency:Creating and Managing the Posts Table
Each time the application starts, SQLAlchemy checks for the existence of theposts table in the database. If the table is missing, it will be automatically created based on the definition in models.py. You can inspect the table structure using tools like PgAdmin.

Cleaning Up the Main Application
To keep your main application file concise, consider migrating the database dependency function (get_db) to the database.py file. You can then import get_db in your main.py as shown below:
Final Remarks
Your FastAPI application is now configured with SQLAlchemy for managing database connections via a session dependency. The posts table is automatically created based on the model inmodels.py, and you can further develop endpoints to execute more complex queries and operations.
With this setup, you now have a robust foundation for database operations in your FastAPI project. In future articles, we will explore adding additional columns (like timestamps) and handling more advanced database interactions.