Learn FastAPI ยท 7/14

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.

bash
pip install fastapi uvicorn sqlalchemy

If 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.

python
# 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. The connect_args are needed only for SQLite to allow multiple threads to interact with the database.
  • sessionmaker: This is a factory for creating new Session objects. 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:

python
# 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.

python
# 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 like primary_key=True to 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.

python
# 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 = True

Notice 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.

python
# 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_post

What's happening?

  1. We create a Post model instance.
  2. db.add(): We add this new object to our session.
  3. db.commit(): This saves the changes to the database.
  4. db.refresh(): This updates our db_post object with any new data from the database, like the generated id.

Read

To read data, we'll use the db.query() method.

python
# 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.

python
# 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_post

Delete

To delete an object, we first fetch it and then use db.delete().

python
# 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_post

Now, 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:

bash
pip install alembic

Then, in your project's root directory, run:

bash
alembic init alembic

This 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.

  1. alembic.ini: Set your database URL.

    ini
    sqlalchemy.url = sqlite:///./sql_app.db
  2. alembic/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.

  1. Generate a migration script:

    bash
    alembic 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/versions directory that contains the necessary changes.

  2. Apply the migration:

    bash
    alembic upgrade head

    This 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

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:

  1. Database Configuration: Set up the SQLAlchemy engine for an in-memory SQLite database. Then, create the SessionLocal class using sessionmaker and the Base class using declarative_base.
  2. 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.
  3. Database Session Dependency: Implement the get_db dependency function. This function must create a new database session for a request, yield it to the path operation, and then guarantee the session is closed in a finally block.
  4. Create Endpoint: Complete the create_user path operation function. It should:
    • Accept user data via the UserCreate Pydantic model.
    • Use the get_db dependency to get a database session.
    • Create a new User model instance from the incoming data.
    • Add the new User instance to the session, commit the transaction, and refresh the instance to populate the id from the database.

Expected result

Your final code should correctly implement all the TODO sections.

  1. engine should be created using create_engine with the specified URL.
  2. SessionLocal should be a sessionmaker configured with autocommit=False, autoflush=False, and bound to the engine.
  3. Base should be an instance of declarative_base().
  4. The User model should have email defined as a Column of type String with unique=True and index=True, and full_name as a Column of type String.
  5. The get_db function must yield db inside the try block and call db.close() inside the finally block.
  6. The create_user function must call db.add(db_user), db.commit(), and db.refresh(db_user) in the correct order to persist the new user and update the db_user instance with the new ID from the database.
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.