Database Integration with SQLAlchemy
8 min read
๐ Database Integration with SQLAlchemy
Welcome, intrepid coder! So, you've built a nifty FastAPI application, and it's zipping along faster than a caffeinated cheetah. But what happens when you need to remember things? Right now, your app has the memory of a goldfish. Every time it restarts, POOF, all the data is gone. That's where a database comes in, and SQLAlchemy is our trusty multitool to connect our Python code to the database without getting our hands dirty with raw SQL.
The Problem: We need a way to store and retrieve data persistently. Imagine building a social media app where all the posts disappear every time the server restarts. Not ideal, right?
The Solution: We'll use a database to store our data. SQLAlchemy, an Object-Relational Mapper (ORM), will act as a translator between our Python objects and the relational database tables. This means we can think in terms of Python classes and objects, and SQLAlchemy will handle the nitty-gritty of SQL queries.
1. Setting Up SQLAlchemy and Database Sessions ๐ฉ
First things first, let's get our tools ready. Think of this as preparing your workshop before you start building.
Installation
We need to install FastAPI, an ASGI server like Uvicorn, SQLAlchemy, and a database driver. For this guide, we'll use SQLite because it's built into Python and is super easy to get started with. For production, you'd likely use something more robust like PostgreSQL.
pip install fastapi uvicorn sqlalchemyIf you were using PostgreSQL, you would also need a driver like psycopg2-binary.
The Database Connection
Now, let's establish a connection to our database. In a real-world application, you'd want to organize your project into different files. Let's create a database.py file.
# database.py
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db"
# For PostgreSQL, it would look like this:
# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db"
engine = create_engine(
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()What's happening here?
create_engine: This function from SQLAlchemy creates a new "engine" that will manage connections to our database. Theconnect_argsare needed only for SQLite to allow multiple threads to interact with the database.sessionmaker: This is a factory for creating newSessionobjects. A session is our main interface for talking to the database. Think of it as a temporary workspace for all the database objects related to a single request.declarative_base: This function returns a base class that our ORM models will inherit from.
Database Sessions: The Heart of the Operation
A Session object is your window into the database. You'll use it to query, add, update, and delete data. It's crucial to manage these sessions properly to avoid issues like connection leaks. The best practice in FastAPI is to have a single session per request and then close it. We can achieve this elegantly with FastAPI's dependency injection system.
In your main.py (or a dedicated dependencies.py), you would add this:
# main.py (or wherever your FastAPI app is)
from .database import SessionLocal
# Dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()This get_db function is a dependency that will create a new session for each request, yield it to the path operation function, and then make sure to close it, even if an error occurs.
2. Defining Database Models and Table Schemas ๐๏ธ
Now that we have our connection set up, it's time to define what our data looks like. In the world of ORMs, we do this by creating Python classes that inherit from the Base we created earlier. These classes are called "models" and they map to tables in our database.
Let's imagine we're building a simple blog. We'll need a Post model. We'll define this in a models.py file.
# models.py
from sqlalchemy import Column, Integer, String
from .database import Base
class Post(Base):
__tablename__ = "posts"
id = Column(Integer, primary_key=True, index=True)
title = Column(String, index=True)
content = Column(String)Let's break it down:
__tablename__ = "posts": This tells SQLAlchemy the name of the database table that will be mapped to this class.Column: This is used to define a column in our table. We specify the data type (e.g.,Integer,String) and other options likeprimary_key=Trueto mark it as the primary key for the table.
A Funny Exaggeration: If you forget to define your models, it's like trying to build a house with imaginary bricks. Your app will have no idea where to store anything, and your data will just float away into the digital ether.
A Quick Word on Pydantic vs. SQLAlchemy Models
It's a common point of confusion. Here's the deal:
- SQLAlchemy Models: Define the structure of your database tables. They are concerned with how data is stored.
- Pydantic Models (Schemas): Define the shape of the data for your API. They are used for data validation of incoming requests and formatting outgoing responses.
You'll often have a Pydantic schema that corresponds to your SQLAlchemy model, but they serve different purposes.
# schemas.py
from pydantic import BaseModel
class PostBase(BaseModel):
title: str
content: str | None = None
class PostCreate(PostBase):
pass
class Post(PostBase):
id: int
class Config:
from_attributes = TrueNotice the Config class with from_attributes = True. This tells Pydantic to read the data from an ORM model's attributes, not just a dictionary.
3. Performing CRUD Operations (Create, Read, Update, Delete) ๐ ๏ธ
CRUD operations are the bread and butter of most applications. Let's see how we can perform these operations using our SQLAlchemy session. It's a good practice to put these database interaction functions in a separate crud.py file.
Create
To create a new post, we'll create an instance of our Post model and add it to our session.
# crud.py
from sqlalchemy.orm import Session
from . import models, schemas
def create_post(db: Session, post: schemas.PostCreate):
db_post = models.Post(title=post.title, content=post.content)
db.add(db_post)
db.commit()
db.refresh(db_post)
return db_postWhat's happening?
- We create a
Postmodel instance. db.add(): We add this new object to our session.db.commit(): This saves the changes to the database.db.refresh(): This updates ourdb_postobject with any new data from the database, like the generatedid.
Read
To read data, we'll use the db.query() method.
# crud.py
def get_post(db: Session, post_id: int):
return db.query(models.Post).filter(models.Post.id == post_id).first()
def get_posts(db: Session, skip: int = 0, limit: int = 100):
return db.query(models.Post).offset(skip).limit(limit).all()Here, db.query(models.Post) starts a query on the posts table. We can then chain methods like filter(), offset(), limit(), and finally first() or all() to get our results.
Update
Updating is a combination of reading and then modifying the object in the session.
# crud.py
def update_post(db: Session, post_id: int, post: schemas.PostCreate):
db_post = db.query(models.Post).filter(models.Post.id == post_id).first()
if db_post:
db_post.title = post.title
db_post.content = post.content
db.commit()
db.refresh(db_post)
return db_postDelete
To delete an object, we first fetch it and then use db.delete().
# crud.py
def delete_post(db: Session, post_id: int):
db_post = db.query(models.Post).filter(models.Post.id == post_id).first()
if db_post:
db.delete(db_post)
db.commit()
return db_postNow, in your main.py, you can create API endpoints that use these CRUD functions.
4. Managing Database Migrations with Alembic ๐
So, you've built your application, and it's working beautifully. But then, you realize you need to add a new column to your posts table. What do you do? You could drop the entire database and recreate it, but you'd lose all your data! This is where a database migration tool like Alembic comes to the rescue.
Alembic allows you to manage changes to your database schema in a version-controlled way.
Installation and Initialization
First, install Alembic:
pip install alembicThen, in your project's root directory, run:
alembic init alembicThis will create an alembic directory and an alembic.ini file.
Configuration
You'll need to configure Alembic to know about your database and your models.
alembic.ini: Set your database URL.inisqlalchemy.url = sqlite:///./sql_app.dbalembic/env.py: This is where you tell Alembic about your SQLAlchemy models.python# alembic/env.py from my_project.models import Base # Import your Base from your models target_metadata = Base.metadata
Creating and Applying Migrations
Now for the magic. Let's say you've added a new author column to your Post model.
Generate a migration script:
bashalembic revision --autogenerate -m "Add author column to posts"Alembic will compare your models to the current state of the database and generate a Python script in the
alembic/versionsdirectory that contains the necessary changes.Apply the migration:
bashalembic upgrade headThis command will run the migration script and apply the changes to your database.
An Interesting Fact: Think of Alembic as a time machine for your database schema. You can move forward (upgrade) and backward (downgrade) through your migration history, making it incredibly powerful for development and deployment.
๐ Further Reading
- FastAPI SQL (Relational) Databases: https://fastapi.tiangolo.com/tutorial/sql-databases/
- SQLAlchemy ORM Tutorial: https://docs.sqlalchemy.org/en/20/orm/tutorial.html
- Alembic Tutorial: https://alembic.sqlalchemy.org/en/latest/tutorial.html
Challenge
Challenge: Implement a Database-Backed "Create" Endpoint
You are tasked with building a FastAPI endpoint that creates and persists new records to a database using SQLAlchemy. Your goal is to correctly configure the database connection, define the ORM model, create a session management dependency, and implement the logic for adding a new record within a path operation.
Requirements:
- Database Configuration: Set up the SQLAlchemy engine for an in-memory SQLite database. Then, create the
SessionLocalclass usingsessionmakerand theBaseclass usingdeclarative_base. - ORM Model: Define a SQLAlchemy model class named
User. It must map to a"users"table and include the following columns:id: An integer, the primary key, and indexed.email: A unique string, indexed.full_name: A string.
- Database Session Dependency: Implement the
get_dbdependency function. This function must create a new database session for a request,yieldit to the path operation, and then guarantee the session is closed in afinallyblock. - Create Endpoint: Complete the
create_userpath operation function. It should:- Accept user data via the
UserCreatePydantic model. - Use the
get_dbdependency to get a database session. - Create a new
Usermodel instance from the incoming data. - Add the new
Userinstance to the session, commit the transaction, and refresh the instance to populate theidfrom the database.
- Accept user data via the
Expected result
Your final code should correctly implement all the TODO sections.
engineshould be created usingcreate_enginewith the specified URL.SessionLocalshould be asessionmakerconfigured withautocommit=False,autoflush=False, and bound to theengine.Baseshould be an instance ofdeclarative_base().- The
Usermodel should haveemaildefined as aColumnof typeStringwithunique=Trueandindex=True, andfull_nameas aColumnof typeString. - The
get_dbfunction mustyield dbinside thetryblock and calldb.close()inside thefinallyblock. - The
create_userfunction must calldb.add(db_user),db.commit(), anddb.refresh(db_user)in the correct order to persist the new user and update thedb_userinstance with the new ID from the database.