FastAPI · Chapter 6 of 6
FastAPI with SQLAlchemy: models, sessions and testing
15 min study · Examples checked with FastAPI 0.163 and SQLAlchemy 2.1 on Python 3.14 ·
The API from chapter 5 forgets everything on restart. This chapter stores lessons in a database through SQLAlchemy, the most widely used Python database toolkit, and its ORM (object-relational mapper), which maps Python classes to tables. The routes barely change, because the storage arrives through a dependency, as before. The example uses SQLite, which keeps the database in a single file and needs no server; switching to PostgreSQL later mostly means changing the connection URL.
Install and define the model
Install SQLAlchemy into the project environment with python -m pip install sqlalchemy. The database setup and the table definition go into database.py:
from collections.abc import Iterator
from sqlalchemy import String, UniqueConstraint, create_engine
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column
engine = create_engine("sqlite:///study.db")
class Base(DeclarativeBase):
pass
class Lesson(Base):
__tablename__ = "lessons"
__table_args__ = (UniqueConstraint("title"),)
id: Mapped[int] = mapped_column(primary_key=True)
title: Mapped[str] = mapped_column(String(120))
minutes: Mapped[int]
def get_session() -> Iterator[Session]:
with Session(engine) as session:
yield session
The engine manages connections to the database named by the URL; sqlite:///study.db is a file next to the app, and a PostgreSQL URL looks like postgresql+psycopg://user:password@host/dbname (keep the password in an environment variable, not in code). Every model class inherits from one Base. Mapped[int] declares a column and its Python type; mapped_column adds details such as the primary key or a maximum string length, and plain Mapped[int] means a required integer column. UniqueConstraint("title") makes the database itself refuse a second lesson with the same title, which is reliable even when two requests arrive at the same moment, unlike the check in Python from chapter 5.
get_session is a dependency with yield. FastAPI runs the code before yield when a request starts, passes the session to the handler, and finishes the with block, closing the session, after the response is done. Each request therefore gets its own session, and no session is shared between concurrent requests.
The API on top of the database
from contextlib import asynccontextmanager
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, Query, status
from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from database import Base, Lesson, engine, get_session
class LessonIn(BaseModel):
title: str = Field(min_length=3, max_length=120)
minutes: int = Field(ge=1, le=180)
class LessonOut(LessonIn):
model_config = ConfigDict(from_attributes=True)
id: int
@asynccontextmanager
async def lifespan(app: FastAPI):
Base.metadata.create_all(engine) # fine for learning; use migrations in production
yield
engine.dispose()
app = FastAPI(lifespan=lifespan)
DB = Annotated[Session, Depends(get_session)]
@app.get("/lessons", response_model=list[LessonOut])
def list_lessons(db: DB, limit: Annotated[int, Query(ge=1, le=100)] = 20, offset: int = 0):
query = select(Lesson).order_by(Lesson.id).offset(offset).limit(limit)
return db.scalars(query).all()
@app.post("/lessons", response_model=LessonOut, status_code=status.HTTP_201_CREATED)
def create_lesson(data: LessonIn, db: DB):
lesson = Lesson(**data.model_dump())
db.add(lesson)
try:
db.commit()
except IntegrityError:
db.rollback()
raise HTTPException(status_code=409, detail="A lesson with this title exists")
db.refresh(lesson)
return lesson
@app.get("/lessons/{lesson_id}", response_model=LessonOut)
def read_lesson(lesson_id: int, db: DB):
lesson = db.get(Lesson, lesson_id)
if lesson is None:
raise HTTPException(status_code=404, detail="Lesson not found")
return lesson
The Pydantic models stay separate from the ORM class: LessonIn and LessonOut describe the API, Lesson describes the table. ConfigDict(from_attributes=True) lets LessonOut read the attributes of a Lesson object, so handlers can return ORM objects and response_model converts them. Keeping the two apart means a new database column, such as an internal flag, never shows up in the API by accident.
Reading with select
select(Lesson).order_by(Lesson.id).offset(offset).limit(limit) builds a SQL query; db.scalars(query).all() runs it and returns Lesson objects. The explicit order_by matters for pagination: without it, the database may return rows in any order, and pages could overlap or skip rows. For a single row by primary key, db.get(Lesson, lesson_id) returns the object or None, which the handler turns into a 404. Filters are written in Python and become SQL parameters, such as select(Lesson).where(Lesson.minutes <= 30), so values are never pasted into SQL text (the same rule as in the SQLite section of the Python track).
Writing and committing
db.add(lesson) stages the new object, and db.commit() writes it in a transaction. Nothing is saved until the commit. If the commit fails, here because the unique constraint rejects a duplicate title, SQLAlchemy raises IntegrityError; the handler rolls the session back and answers 409. db.refresh(lesson) reloads the row, so the id assigned by the database is available for the response. Commit before returning: a handler that returned 201 and only then failed to commit would tell the client something false.
Running the app, creating a lesson, stopping it and starting it again shows the point of the exercise:
POST /lessons {"title": "Variables", "minutes": 20} -> 201 {"title": "Variables", "minutes": 20, "id": 1}
POST /lessons {"title": "Variables", "minutes": 5} -> 409
(restart)
GET /lessons/1 -> 200 {"title": "Variables", "minutes": 20, "id": 1}
Startup, migrations and async
lifespan runs code when the application starts and stops. Here it creates missing tables and, on shutdown, closes the engine’s connections. create_all only creates tables that don’t exist; it never adds a column to an existing table. Real projects therefore use a migration tool, normally Alembic for SQLAlchemy, which records every schema change as a versioned script that runs the same way in development, testing and production.
The handlers are plain def, because this SQLAlchemy setup is synchronous and FastAPI runs them in a thread pool. SQLAlchemy also has an async API (create_async_engine, AsyncSession) with async drivers such as aiosqlite or asyncpg; then the handlers become async def and await every database call. Never mix them by calling the synchronous session inside async def, which blocks the event loop (asyncio chapter).
Testing against a throwaway database
Tests should never touch the development database. Override the session dependency with one bound to an in-memory SQLite database: in a pytest fixture, create an engine with create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool), call Base.metadata.create_all on it, and set app.dependency_overrides[get_session] to a generator that yields a Session on that engine. StaticPool keeps the single in-memory connection alive between requests, and check_same_thread=False lets TestClient’s worker thread use it. Clear the overrides after each test. A test can then create a lesson, read it back, post a duplicate and expect 409, all against a database that disappears when the test ends.
Practice
Add DELETE /lessons/{lesson_id} (204, or 404 when missing) and PATCH /lessons/{lesson_id} that applies exclude_unset changes to the ORM object. Then add a nullable description column and notice that create_all doesn’t add it to your existing study.db.
Answer check: delete with db.delete(lesson) and db.commit(). For PATCH, loop over the changes with setattr(lesson, field, value), commit inside the same try/except IntegrityError as create, so renaming to an existing title gives 409. The new column only appears after deleting the file or, properly, after an Alembic migration such as alembic revision --autogenerate followed by alembic upgrade head.
Summary
SQLAlchemy maps classes to tables with Mapped and mapped_column, and a dependency with yield gives each request its own session. Keep Pydantic schemas apart from ORM models, query with select and an explicit order, let constraints enforce uniqueness, commit before reporting success and map IntegrityError to 409. Use migrations for schema changes, and override the session in tests.