DEV Community

prasanna Kumar
prasanna Kumar

Posted on

Mastering Database Migrations in FastAPI with Alembic

If you're coming from Django, you might miss the built-in makemigrations. In the FastAPI world, Alembic is the industry standard. It’s powerful, but the initial setup can feel like a "configuration maze."

Here is the simplified 3-step workflow to get you up and running without the headache.

1. The "Big Three" Setup Steps

To get Alembic talking to your FastAPI models, you need to configure these three areas:

A. The Initialization

Run this in your terminal to create your migration environment:

alembic init migrations
Enter fullscreen mode Exit fullscreen mode

This creates a migrations/ folder and an alembic.ini file.

B. The alembic.ini (The Address Book)

This file tells Alembic where your database lives. Find the line sqlalchemy.url and update it.

Pro-Tip: If you use a .env file, leave this blank and load it dynamically in env.py to keep your credentials secure!

C. The env.py (The Brain)

This is the most critical file. Inside migrations/env.py, you must link your models:

# migrations/env.py
from my_app.db.base import Base  # Import your SQLAlchemy Base/SQLModel
target_metadata = Base.metadata    # Link it here so Alembic "sees" your tables
Enter fullscreen mode Exit fullscreen mode

2. The Development Loop

Once setup is done, you only need to remember this 3-step loop whenever you change your database schema:
1. Change: Edit your Python models (e.g., add a bio column to your User class).

2. Revision: Generate the migration script:

alembic revision --autogenerate -m "add user bio"
Enter fullscreen mode Exit fullscreen mode
3. Upgrade: Apply the changes to the live database:
alembic upgrade head
Enter fullscreen mode Exit fullscreen mode

3. Important "Gotchas" to Remember

The Autogenerate Trap: Alembic isn't psychic. It can miss renamed columns or specific Enum changes. Always check the generated file in migrations/versions/ before running the upgrade.

Async Support: Using AsyncSession? You must initialize with the async template:

alembic init -t async migrations
Enter fullscreen mode Exit fullscreen mode

The alembic_version Table: Alembic creates a table in your DB to track the current migration ID. If your DB and code get out of sync, this is the first place to look.

inspired by: Cheat sheet of 'Alembic' commands

Top comments (0)