0
0
FastAPIframework~5 mins

Alembic migrations in FastAPI

Choose your learning style9 modes available
Introduction

Alembic helps you change your database structure safely over time. It keeps track of changes so your app and database stay in sync.

When you add a new table or column to your database in a FastAPI app.
When you want to update or remove existing database columns without losing data.
When you need to share database changes with your team easily.
When deploying your FastAPI app and want to apply database updates automatically.
When you want to keep a history of all database changes for safety and rollback.
Syntax
FastAPI
alembic init <directory>
alembic revision -m "message"
alembic upgrade head
alembic downgrade -1

alembic init creates migration setup files.

alembic revision makes a new migration file with your changes.

Examples
Sets up Alembic in a folder named alembic.
FastAPI
alembic init alembic
Creates a new migration file with the message describing the change.
FastAPI
alembic revision -m "add users table"
Applies all new migrations to update the database to the latest version.
FastAPI
alembic upgrade head
Reverts the last migration, useful if you want to undo a change.
FastAPI
alembic downgrade -1
Sample Program

This example shows a simple User table with SQLAlchemy in FastAPI style. Alembic commands are used in the terminal to manage migrations.

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

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)

# Create SQLite engine
engine = create_engine('sqlite:///./test.db')

# Create tables
Base.metadata.create_all(bind=engine)

# Alembic migration steps (run in terminal):
# 1. alembic init alembic
# 2. Configure alembic.ini to use sqlite:///./test.db
# 3. alembic revision -m "create users table"
# 4. Edit migration file to create users table if not autogenerated
# 5. alembic upgrade head

print("User table created and migration setup done.")
OutputSuccess
Important Notes

Always check your migration files before applying to avoid mistakes.

Use descriptive messages in alembic revision -m to remember changes easily.

Keep your database URL consistent between your app and Alembic config.

Summary

Alembic helps manage database changes safely over time.

Use Alembic commands to create, apply, and undo migrations.

Keep migration files clear and consistent with your app models.