0
0
FastapiHow-ToBeginner · 4 min read

How to Run Migrations in FastAPI with Alembic

To run migrations in FastAPI, use Alembic, a database migration tool that works with SQLAlchemy. Initialize Alembic in your project, create migration scripts with alembic revision --autogenerate, and apply them using alembic upgrade head.
📐

Syntax

Here are the main commands to run migrations with Alembic in a FastAPI project:

  • alembic init alembic: Initializes Alembic configuration and folder.
  • alembic revision --autogenerate -m "message": Creates a new migration script by comparing models and database.
  • alembic upgrade head: Applies all pending migrations to the database.

You configure Alembic to connect to your database and import your SQLAlchemy models for accurate migration scripts.

bash
alembic init alembic
alembic revision --autogenerate -m "create tables"
alembic upgrade head
💻

Example

This example shows a minimal FastAPI project using SQLAlchemy and Alembic to run migrations.

It demonstrates creating a user table and applying migrations.

python
from fastapi import FastAPI
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

DATABASE_URL = "sqlite:///./test.db"

engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, index=True)

app = FastAPI()

# Alembic setup (in alembic/env.py) should import User and Base

# Run these commands in terminal:
# alembic init alembic
# (edit alembic.ini and alembic/env.py to set DATABASE_URL and import models)
# alembic revision --autogenerate -m "create users table"
# alembic upgrade head

@app.get("/users")
def read_users():
    db = SessionLocal()
    users = db.query(User).all()
    db.close()
    return users
Output
INFO [alembic.runtime.migration] Running upgrade -> head INFO [alembic.runtime.migration] Upgrade successful
⚠️

Common Pitfalls

Common mistakes when running migrations in FastAPI include:

  • Not configuring Alembic to import your SQLAlchemy models, so --autogenerate creates empty migrations.
  • Forgetting to set the correct database URL in alembic.ini or environment variables.
  • Running migrations without creating revision scripts first.
  • Modifying models without generating new migration scripts.

Always check your migration scripts before applying to avoid unwanted schema changes.

python
Wrong way:
# Forgetting to import models in alembic/env.py

Right way:
# In alembic/env.py, add:
from myapp.models import Base

target_metadata = Base.metadata
📊

Quick Reference

CommandDescription
alembic init alembicCreate Alembic config and folders
alembic revision --autogenerate -m "msg"Generate migration script from model changes
alembic upgrade headApply all migrations to the database
alembic downgrade -1Revert last migration

Key Takeaways

Use Alembic with FastAPI and SQLAlchemy to manage database migrations safely.
Always generate migration scripts with --autogenerate after model changes.
Configure Alembic to import your SQLAlchemy models for accurate migrations.
Apply migrations using alembic upgrade head to update your database schema.
Review migration scripts before applying to avoid unintended changes.