FastAPI with SQLAlchemy Models and Alembic Migrations: A Table from a Class, a Session per Request
A Post model in SQLAlchemy 2, an engine and a get_db dependency that yields one session per request, then Alembic turns the model into a posts table and shows its SQL before running it. Three timed routes show when async def helps: 3.0 s with a blocking call, 1.0 s with def or await.
What you will learn
- Write a SQLAlchemy 2 model with Mapped type hints
- Give each FastAPI request its own session with a yield dependency
- Create a table with an Alembic autogenerated migration and read its SQL first
- Explain why async def with a blocking session is slower than plain def
Before you start
- FastAPI path, query and body parameters
- Basic SQL tables and rows
Until now, our FastAPI routes kept nothing. Stop the server and every post is gone. A database keeps the data across restarts, and a model tells Python what that data looks like.
We'll use SQLite throughout this track. It's a database kept in a single file, here blog.db, so there's no database server to install. Inside it we want one table, posts, with four columns: id, title, body and created. We won't write that SQL by hand. With SQLAlchemy, one Python class stands for the table and one object becomes one row. That's an ORM, an object relational mapper.
Add the packages
This builds on the small app from FastAPI Path, Query and Body Parameters. Add SQLAlchemy, Alembic and an async SQLite driver we'll use at the end:
uv add "sqlalchemy[asyncio]" alembic aiosqlite
Resolved 67 packages in 61ms
Installed 5 packages in 173ms
+ aiosqlite==0.22.1
+ alembic==1.20.1
+ greenlet==3.5.6
+ mako==1.4.3
+ sqlalchemy==2.1.8
The Post model
models.py:
from datetime import datetime, timezone
from sqlalchemy import DateTime, String, Text
from sqlalchemy.orm import (DeclarativeBase, Mapped,
mapped_column)
def now():
return datetime.now(timezone.utc)
class Base(DeclarativeBase):
pass
class Post(Base):
__tablename__ = "posts"
id: Mapped[int] = mapped_column(primary_key=True)
title: Mapped[str] = mapped_column(String(200))
body: Mapped[str] = mapped_column(Text)
created: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=now)
Basecomes fromDeclarativeBase. Every model inherits from it, so SQLAlchemy keeps a list of all our tables inBase.metadata.__tablename__is the name the table gets in the database.Mapped[int]andMapped[str]are type hints that tell SQLAlchemy each column's type, and that it can't be empty.createddefaults to ournow()function, which usesdatetime.now(timezone.utc). Older code often usesdatetime.utcnow, which is deprecated.
Engine, session and get_db
database.py:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
engine = create_engine("sqlite:///blog.db")
SessionLocal = sessionmaker(bind=engine)
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
The engine knows where the database is and how to talk to it. SessionLocal is a factory for sessions, and a session is one conversation with the database: you add objects, commit, and read. get_db opens a session, and yield hands it to whoever asked. When the request is finished, the code after yield runs, and finally closes the session even if something went wrong.
Why migrations
We have a model, but blog.db still has no posts table. The blogs later in this track call Base.metadata.create_all at startup. It creates any table that's missing, and that's all it does. Add a column to Post later and create_all sees the table already exists, so the new column never shows up.
Alembic solves this with migrations. Each migration is a small file with one step. The files are chained in order, and the database keeps a note of the last step it ran, so any copy of the database can be brought up to date the same way.
Setting up Alembic
uv run alembic init alembic
This creates an alembic folder with env.py and a versions folder, plus alembic.ini at the top. Two edits link it to our project. In alembic.ini, the address starts as a placeholder:
sqlalchemy.url = driver://user:pass@localhost/dbname
We change it to the same address our engine uses:
sqlalchemy.url = sqlite:///blog.db
And in alembic/env.py, Alembic gets to see our models:
from models import Base
target_metadata = Base.metadata
Autogenerate a migration
uv run alembic revision --autogenerate -m "create posts table"
Alembic compares the models with the database, sees the missing table, and writes alembic/versions/7bfda629898d_create_posts_table.py. The part that matters:
revision: str = '7bfda629898d'
down_revision: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('posts',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(length=200), nullable=False),
sa.Column('body', sa.Text(), nullable=False),
sa.Column('created', sa.DateTime(timezone=True), nullable=False),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('posts')
# ### end Alembic commands ###
upgrade creates the table with every column we wrote. downgrade drops it, so you can step back. down_revision is None because this is the first step in the chain. Autogenerate gives you a draft, so read the file before you run it, the same way you'd review a diff from an AI agent.
Read the SQL before it runs
uv run alembic upgrade head --sql
CREATE TABLE alembic_version (
version_num VARCHAR(32) NOT NULL,
CONSTRAINT alembic_version_pkc PRIMARY KEY (version_num)
);
-- Running upgrade -> 7bfda629898d
CREATE TABLE posts (
id INTEGER NOT NULL,
title VARCHAR(200) NOT NULL,
body TEXT NOT NULL,
created DATETIME NOT NULL,
PRIMARY KEY (id)
);
INSERT INTO alembic_version (version_num) VALUES ('7bfda629898d') RETURNING version_num;
head means the latest step. With --sql, nothing runs: Alembic only prints what it would do. First the small alembic_version table where the database keeps its note, then our model in plain SQL, then the note itself.
Upgrade to head
uv run alembic upgrade head
uv run alembic current
uv run alembic history
INFO [alembic.runtime.migration] Running upgrade -> 7bfda629898d, create posts table
7bfda629898d (head)
<base> -> 7bfda629898d (head), create posts table
blog.db now has two tables, alembic_version and posts. current says this database is at head, and history shows the chain. When the model changes, it's the same two commands again: revision --autogenerate, then upgrade head. The Flask and Django versions of this idea are in Flask-SQLAlchemy Models and Flask-Migrate and Django Models, Migrations and the Admin.
A session per request in FastAPI
main.py:
from datetime import datetime
from fastapi import Depends, FastAPI
from pydantic import BaseModel, ConfigDict
from sqlalchemy import select
from sqlalchemy.orm import Session
from database import get_db
from models import Post
app = FastAPI()
class PostIn(BaseModel):
title: str
body: str
class PostOut(PostIn):
model_config = ConfigDict(from_attributes=True)
id: int
created: datetime
@app.get("/")
async def home():
return {"message": "Hello blog, my first app."}
@app.post("/posts", response_model=PostOut)
def create_post(data: PostIn,
db: Session = Depends(get_db)):
post = Post(title=data.title, body=data.body)
db.add(post)
db.commit()
db.refresh(post)
return post
@app.get("/posts", response_model=list[PostOut])
def list_posts(db: Session = Depends(get_db)):
return db.scalars(select(Post)).all()
PostIn is what a client sends. PostOut adds id and created, and from_attributes=True lets Pydantic read them straight off a Post object. db: Session = Depends(get_db) works like any dependency: FastAPI calls get_db and passes in the session it yields.
In create_post, db.add puts the object in the session, commit writes the row, and refresh reads it back so the object has its new id and created. Two posts from the run:
POST /posts {"title": "Hello", "body": "My first post."}
200 {"title":"Hello","body":"My first post.","id":1,"created":"2026-11-15T18:13:59.471579"}
POST /posts {"title": "Packing a bag", "body": "Light is best."}
200 {"title":"Packing a bag","body":"Light is best.","id":2,"created":"2026-11-15T18:13:59.505265"}
list_posts runs select(Post), and db.scalars gives back Post objects, not raw rows:
GET /posts
200 [{"title":"Hello","body":"My first post.","id":1,"created":"2026-11-15T18:13:59.471579"},{"title":"Packing a bag","body":"Light is best.","id":2,"created":"2026-11-15T18:13:59.505265"}]
SQLite has no time zone type, so created comes back without an offset. We saved it in UTC, so we know what it means. And a post with no body never reaches the session:
POST /posts (no body)
422 {"detail":[{"type":"missing","loc":["body","body"],"msg":"Field required","input":{"title":"No body"}}]}
async def and a blocking session
Notice that create_post and list_posts are plain def, and only home is async def. Here's why.
Every async def route runs on one event loop, a single worker that takes turns between requests. It can only switch to another request at an await. A normal SQLAlchemy Session is blocking: a query has no await, so while it runs, the loop is stuck and the whole queue waits. A plain def route is different. FastAPI runs it in a thread pool, so a slow one doesn't stop the others.
To measure it, blocking.py has three routes that each wait one second:
import asyncio
import time
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def root():
return {"ok": True}
@app.get("/blocks")
async def blocks():
time.sleep(1)
return {"route": "async def + blocking call"}
@app.get("/threads")
def threads():
time.sleep(1)
return {"route": "def + blocking call"}
@app.get("/awaits")
async def awaits():
await asyncio.sleep(1)
return {"route": "async def + await"}
From the run, three requests sent at the same time to each route:
| Route | What's inside | Total for 3 requests |
|---|---|---|
/blocks | async def + time.sleep(1) | 3.0 s |
/threads | def + time.sleep(1) | 1.0 s |
/awaits | async def + await asyncio.sleep(1) | 1.0 s |
So async def isn't faster on its own. It only helps when the slow work inside is awaited. Put a blocking call in it and it's worse than plain def, because the requests have to wait their turn.
Two safe ways to use the database
The first is what main.py already does: plain def routes with the normal Session, run in the thread pool. The second is fully async, which is what aiosqlite is for. async_check.py:
import asyncio
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import (AsyncSession,
create_async_engine)
from models import Post
URL = "sqlite+aiosqlite:///blog.db"
engine = create_async_engine(URL)
async def main():
async with AsyncSession(engine) as session:
count = await session.scalar(
select(func.count()).select_from(Post))
print("posts:", count)
asyncio.run(main())
posts: 2
Same two rows, read with an await. Either way works. The mistake is mixing them: async def over a blocking session. The finished blog in this track does exactly that, and it's measured in How a Request and a Login Flow Through the FastAPI Blog. Another look at the def vs async def choice, for an AI service, is in FastAPI for AI Services.
Common mistakes
- Relying on
create_allfor changes. It only creates missing tables. A new column needs a migration. - Running an autogenerated migration unread. Check the file, and use
upgrade head --sqlto see the SQL first. - Different addresses in
alembic.iniand the engine. Alembic then migrates a different file from the one the app reads. - Forgetting
target_metadata = Base.metadata. Autogenerate can't see your models and writes an empty migration. - Sharing one session across requests. Use the
get_dbdependency so each request gets its own and it's always closed. async defwith a normalSession. Use plaindef, or go fully async withAsyncSession.
Quick recap
| Piece | Job | Here |
|---|---|---|
| Model | a class for a table | Post, table posts |
| Engine | where the database is | sqlite:///blog.db |
get_db | one session per request | yield db, then db.close() |
| Migration | one schema step, chained | 7bfda629898d, create posts table |
upgrade head --sql | preview the SQL | CREATE TABLE posts (...) |
def vs async def | thread pool vs event loop | 3.0 s vs 1.0 s for a blocking call |
Try it yourself
Add an optional summary column to Post, typed Mapped[str | None]. Run uv run alembic revision --autogenerate -m "add summary", read the new file (what is its down_revision?), then run uv run alembic upgrade head.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
From a List to a Database in FastAPI: Route, Service, Repository and the SQL SQLAlchemy Sends
Move a FastAPI Book API from an in-memory list to SQLite without changing a single URL. Three layers (route, service, repository), a SQLAlchemy model, and the real SQL each request sends with echo=True.
Docker Compose: Run a FastAPI App and Postgres From One File
A notes API in FastAPI plus Postgres, described in one compose.yaml: the service name as the database host, a named volume, a pg_isready healthcheck with depends_on, and a real run showing notes surviving docker compose down but not down -v.
Docker Health Checks, Networks and Resource Limits: Up Is Not Enough
Make a FastAPI plus Postgres Compose stack ready for a server: config from the environment, logs to stdout, a /health route behind HEALTHCHECK that turns the API unhealthy when the database stops, an internal network that hides the database, and a 256 MB limit that kills a 400 MB allocation with exit code 137.
