Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

FastAPI
  • FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
  • RESTful API Basics: Resources, Methods, Stateless Requests and Status Codes
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • What FastAPI Is: Starlette, Pydantic, uvicorn and What async def Really Gives You
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a FastAPI Blog: Every Folder and File an AI Agent Built, and What to Question
  • Swagger UI and OpenAPI in FastAPI: Reading the Contract Your Code Writes
  • POST, PUT and DELETE in FastAPI: Choosing 201, 200, 204 and 404 on the Server
  • Paging, Sorting and Filtering a REST API in FastAPI
  • API Versioning in FastAPI with an API-Version Header
  • Idempotent REST Methods, HATEOAS and the Maturity Model: Which Requests Are Safe to Repeat
  • A FastAPI REST API End to End: One App Visit, Seven Requests
  • The Book API in FastAPI: A Contract a React Client Can Rely On
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • FastAPI Request and Response Models with Pydantic: Design the JSON on Purpose
  • FastAPI Path, Query and Body Parameters: Reading a 422, response_model and Depends
  • Validation and Problem Details in FastAPI: From a 422 to One Error Shape for the Whole API
  • FastAPI with SQLAlchemy Models and Alembic Migrations: A Table from a Class, a Session per Request
  • From a List to a Database in FastAPI: Route, Service, Repository and the SQL SQLAlchemy Sends
  • Docker Compose: Run a FastAPI App and Postgres From One File
  • Docker Health Checks, Networks and Resource Limits: Up Is Not Enough
  • How a Request and a Login Flow Through a FastAPI Blog: Depends, bcrypt, a Signed Session Cookie and async def
  • Enterprise Integration for an AI App: One Adapter per Edge for SSO, the CRM, a Legacy CSV and Webhooks
  1. Blog
  2. /
  3. FastAPI
  4. /
  5. Databases

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Databases

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)
  • Base comes from DeclarativeBase. Every model inherits from it, so SQLAlchemy keeps a list of all our tables in Base.metadata.
  • __tablename__ is the name the table gets in the database.
  • Mapped[int] and Mapped[str] are type hints that tell SQLAlchemy each column's type, and that it can't be empty.
  • created defaults to our now() function, which uses datetime.now(timezone.utc). Older code often uses datetime.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.

The Post class in models.py is compared by alembic revision --autogenerate, which writes a migration file 7bfda629898d create posts table. alembic upgrade head runs it against blog.db, which gets a posts table and an alembic_version table holding 7bfda629898d. models.py class Post Base.metadata versions/ 7bfda629898d create posts table blog.db posts alembic_version 7bfda629898d revision --autogenerate upgrade head (--sql to preview)
Autogenerate writes the step from the model, upgrade runs it, and the database remembers where it is.

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"}
Three requests sent at once to each route. async def with time.sleep took 3.0 seconds in total. def with time.sleep took 1.0 second. async def with await asyncio.sleep took 1.0 second. Three requests at once, total time async def + time.sleep 3.0 s def + time.sleep 1.0 s async def + await 1.0 s
The same one-second wait, three ways. Only the blocking call inside async def makes the requests queue.

From the run, three requests sent at the same time to each route:

RouteWhat's insideTotal for 3 requests
/blocksasync def + time.sleep(1)3.0 s
/threadsdef + time.sleep(1)1.0 s
/awaitsasync 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_all for changes. It only creates missing tables. A new column needs a migration.
  • Running an autogenerated migration unread. Check the file, and use upgrade head --sql to see the SQL first.
  • Different addresses in alembic.ini and 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_db dependency so each request gets its own and it's always closed.
  • async def with a normal Session. Use plain def, or go fully async with AsyncSession.

Quick recap

PieceJobHere
Modela class for a tablePost, table posts
Enginewhere the database issqlite:///blog.db
get_dbone session per requestyield db, then db.close()
Migrationone schema step, chained7bfda629898d, create posts table
upgrade head --sqlpreview the SQLCREATE TABLE posts (...)
def vs async defthread pool vs event loop3.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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in FastAPI · 21 of 26

Previous
Validation and Problem Details in FastAPI: From a 422 to One Error Shape for the Whole API
Next post
From a List to a Database in FastAPI: Route, Service, Repository and the SQL SQLAlchemy Sends

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.

On this page

  • Add the packages
  • The Post model
  • Engine, session and get_db
  • Why migrations
  • Setting up Alembic
  • Autogenerate a migration
  • Read the SQL before it runs
  • Upgrade to head
  • A session per request in FastAPI
  • async def and a blocking session
  • Two safe ways to use the database
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.