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