Video summary

FastAPI & Alembic - Database Migrations in FastAPI apps

Main summary

Key takeaways

Technology

Summary (Tech concepts + features)

Purpose of Alembic (auto migrations in FastAPI apps)

Alembic is introduced as a lightweight database migration tool for SQLAlchemy-based projects.

Its goal is to help you keep your database schema aligned with your application models:

  • When you change SQLModel model classes in a FastAPI app, Alembic can detect model changes.
  • It can then autogenerate revision files that update the database schema accordingly.
  • This matters because you need to track historical schema changes and manage how your database evolves over time.

Project setup workflow shown

The workflow includes:

  • Install Alembic via pip inside a Python virtual environment.
  • Run alembic init to create:
    • A migrations/ directory
    • An alembic.ini file at the project root
  • Note: the earlier video included an SQLModel-based database creation step (init_db) that created tables directly at startup.

Configuring Alembic for SQLModel models

Configuration is handled via the migrations/env.py file:

  • Import model classes into env.py using table=True—specifically:
    • Band
    • Album
  • Set target_metadata to the SQLModel Base metadata for those table=True models.
    • This tells Alembic what schema to compare against during autogeneration.
  • Configure the database connection URL (the SQLAlchemy URL) in Alembic:
    • Build a path to a local SQLite database file
    • Set sqlalchemy.url dynamically using config.set_main_option(...)

Autogenerating and inspecting migration revisions

To create migrations:

  • Run:
    • alembic revision --autogenerate -m "initial migration"
  • This generates a revision file under:
    • migrations/versions/
  • Key behaviors explained:
    • The first migration typically has down_revision = None.
    • If the database already matches the models, the initially generated migration may have empty upgrade() and downgrade() bodies.

“Clean” approach demonstrated:

  • Delete the existing SQLite database file.
  • Remove the initial migration file.
  • Regenerate the migration so Alembic produces real schema changes.

What the generated migration contains

In the resulting migration:

  • The upgrade() function includes op.create_table(...) for:
    • band
    • album
  • Column definitions derive from SQLModel/SQLAlchemy types (e.g., string/integer/date).
  • Constraints such as primary keys and nullability are included.

Applying migrations to the database

To apply changes:

  • Run alembic upgrade head to apply the latest migration(s).
  • The database schema updates to match the model-defined tables/columns.

Removing redundant schema creation in FastAPI code

To rely on migrations going forward:

  • Remove the FastAPI startup lifespan behavior that called init_db.
  • Shift schema management responsibility fully to Alembic.

Demonstrating schema evolution with a model change

A schema change is shown by modifying the Band SQLModel class:

  • Add a new nullable field:
    • date_formed (subtitle indicates “Date formed”)
  • Example concept: date | None, which maps to a nullable database column.

Then:

  • Run autogeneration again:
    • alembic revision --autogenerate -m "added date formed field to the band model"
  • The new migration includes:
    • op.add_column(...) targeting the band table
    • Column type set to SQLAlchemy Date
    • nullable=True to match date | None
  • The downgrade() includes:
    • op.drop_column(...) to remove the added column

Finally:

  • Apply the migration with alembic upgrade head.
  • Verify the new column in SQLite (via SQL Explorer).

Scalability/maintenance argument

Core takeaway: once Alembic is set up, you can keep the database synced with model changes by repeatedly running:

  1. alembic revision --autogenerate
  2. alembic upgrade head

This is presented as easier/more scalable than handling schema updates outside the app. A similar approach could be adapted for other Python backends (e.g., Flask/Starlette).


Main speakers/sources

  • Speaker: The YouTube creator/host (name not provided in subtitles).
  • Technical sources referenced:
    • Alembic documentation
    • SQLModel
    • SQLAlchemy
    • FastAPI
    • Alembic-generated files:
      • migrations/env.py
      • Revision files
      • alembic.ini

Original video