Script Valley
FastAPI: Build Production Python APIs
Database Integration with SQLAlchemyLesson 3.4

How to use Alembic for database migrations in FastAPI projects

Alembic init, alembic.ini, env.py configuration, autogenerate, upgrade, downgrade, revision, migration history, production migration workflow

Database Migrations with Alembic

Alembic is the SQLAlchemy migration tool. It tracks schema changes in versioned files so you can upgrade and roll back database schemas without losing data.

Setup

pip install alembic
alembic init alembic

This creates an alembic/ directory and alembic.ini. Edit alembic/env.py to point at your models and database URL:

# alembic/env.py
from app.database import Base, DATABASE_URL
from app import models  # noqa: ensure models are imported

config.set_main_option("sqlalchemy.url", DATABASE_URL)
target_metadata = Base.metadata

Generate and run a migration

# Generate migration from model changes
alembic revision --autogenerate -m "add users table"

# Apply migration
alembic upgrade head

# Roll back one step
alembic downgrade -1

--autogenerate compares your ORM models to the current database schema and writes the migration script. Always review the generated file before applying โ€” autogenerate misses some changes like column renames.

Checking migration history

alembic history --verbose
alembic current

Never edit applied migration files. Create a new revision to fix mistakes. In production, run alembic upgrade head as part of your deployment pipeline before starting the app.

Up next

How to use SQLAlchemy async sessions with FastAPI

Sign in to track progress

How to use Alembic for database migrations in FastAPI projects โ€” Database Integration with SQLAlchemy โ€” FastAPI: Build Production Python APIs โ€” Script Valley โ€” Script Valley