Database Migrations with Alembic
Evolve your SQLAlchemy schema safely over time using Alembic: initialize migrations, autogenerate revisions, and apply or roll back changes in a FastAPI project.
Database Migrations with Alembic is a free FastAPI Backend Development Bootcamp lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the FastAPI Backend Development Bootcamp learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Migrations
Your database schema changes as your app grows: new columns, tables, and indexes. Migrations are versioned, repeatable scripts that evolve the schema without losing data. Alembic is the standard tool for SQLAlchemy.
create_all Is Not Enough
Base.metadata.create_all() creates missing tables but never alters existing ones. It cannot add a column to a populated table or track history. Production needs real migrations.
Installing and Initializing
Install Alembic and scaffold its folder. This creates an alembic/ directory and alembic.ini.
pip install alembic
alembic init alembicPointing Alembic at Your Models
In alembic/env.py, set target_metadata to your SQLAlchemy Base.metadata so autogenerate can compare models to the live schema.
from app.database import Base
from app import models # ensure models are imported
target_metadata = Base.metadataSetting the Database URL
Configure the connection string. Reading it from an env var keeps secrets out of source control.
import os
config.set_main_option('sqlalchemy.url', os.environ['DATABASE_URL'])Autogenerating a Revision
Alembic compares your models to the database and writes a migration script with the differences.
alembic revision --autogenerate -m 'add email to users'Anatomy of a Migration
Each script has upgrade() and downgrade(). Upgrade applies the change; downgrade reverses it. Always review autogenerated code before running it.
def upgrade():
op.add_column('users', sa.Column('email', sa.String(), nullable=True))
def downgrade():
op.drop_column('users', 'email')Applying Migrations
Run upgrade head to apply all pending migrations up to the latest revision.
alembic upgrade headRolling Back
Step back one revision with downgrade -1, or to a specific revision id. Rollbacks are why writing accurate downgrade() matters.
alembic downgrade -1Revision Chain Mental Model
Migrations form a linked list: each revision records its down_revision. Alembic walks the chain to know what to apply. Here is the idea in plain Python.
revisions = [
{'id': 'a1', 'down': None},
{'id': 'b2', 'down': 'a1'},
{'id': 'c3', 'down': 'b2'},
]
order = []
cur = 'c3'
by_id = {r['id']: r for r in revisions}
while cur:
order.append(cur)
cur = by_id[cur]['down']
print(list(reversed(order)))Migration Best Practices
Keep migrations safe:
- Review autogenerated scripts; they miss some changes (e.g. column renames).
- Run migrations in CI/CD before deploying code.
- Make additive changes first, remove old columns in a later release.
- Never edit an already-applied migration; create a new one.
Quick Check
Why is Base.metadata.create_all() insufficient for evolving a production schema?
Recap
You added safe schema evolution:
- Initialized Alembic and wired it to your models and DB URL.
- Autogenerated revisions with
upgrade()/downgrade(). - Applied with
upgrade headand reverted withdowngrade. - Followed best practices for reviewing and sequencing migrations.
Frequently asked questions
Is the “Database Migrations with Alembic” lesson free?
Yes — the full text of “Database Migrations with Alembic” is free to read here on the web, and the FastAPI Backend Development Bootcamp course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the FastAPI Backend Development Bootcamp course, upgrade to CoddyKit PRO.
What will I learn in “Database Migrations with Alembic”?
Evolve your SQLAlchemy schema safely over time using Alembic: initialize migrations, autogenerate revisions, and apply or roll back changes in a FastAPI project. You practise FastAPI Backend Development Bootcamp with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start FastAPI Backend Development Bootcamp?
No prior experience is required. FastAPI Backend Development Bootcamp on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Database Migrations with Alembic” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this FastAPI Backend Development Bootcamp lesson?
Yes. Every FastAPI Backend Development Bootcamp lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- SQLAlchemy ORM Fundamentals
- Connecting FastAPI to PostgreSQL
- CRUD Operations with SQLAlchemy
- Database Migrations with Alembic