Alembic helps you change your database structure safely over time. It keeps track of changes so your app and database stay in sync.
Alembic migrations in FastAPI
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
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
alembic.FastAPI
alembic init alembic
FastAPI
alembic revision -m "add users table"FastAPI
alembic upgrade head
FastAPI
alembic downgrade -1Sample 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.")
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.
Practice
1. What is the main purpose of Alembic migrations in a FastAPI project?
easy
Solution
Step 1: Understand Alembic's role
Alembic is a tool designed to manage database schema changes, not web server tasks.Step 2: Identify the correct purpose
It helps developers apply, track, and revert database changes safely during development and deployment.Final Answer:
To manage and apply database schema changes safely over time -> Option AQuick Check:
Alembic = database migrations [OK]
Hint: Alembic is for database schema changes, not web or UI tasks [OK]
Common Mistakes:
- Confusing Alembic with FastAPI routing
- Thinking Alembic serves static files
- Assuming Alembic builds UI components
2. Which Alembic command creates a new migration script file?
easy
Solution
Step 1: Identify commands for migration scripts
The command to create a new migration script isrevisionwith a message describing the change.Step 2: Match the command
alembic revision -m "message"creates a new migration file with the given message.Final Answer:
alembic revision -m "message" -> Option DQuick Check:
revision = create migration script [OK]
Hint: Use 'revision' with -m to create migration scripts [OK]
Common Mistakes:
- Using 'upgrade' to create scripts instead of apply them
- Confusing 'downgrade' with script creation
- Using 'init' after project setup
3. Given this Alembic command sequence:
What happens after running these commands?
alembic revision -m "add users table"alembic upgrade headWhat happens after running these commands?
medium
Solution
Step 1: Understand the revision command
alembic revision -m "add users table"creates a new migration script file describing the addition of the users table.Step 2: Understand the upgrade command
alembic upgrade headapplies all migrations up to the latest, updating the database schema accordingly.Final Answer:
A new migration script is created and the database schema is updated to include the users table -> Option CQuick Check:
revision + upgrade = new migration applied [OK]
Hint: Revision creates script; upgrade applies it to DB [OK]
Common Mistakes:
- Thinking upgrade resets or deletes migrations
- Confusing downgrade with upgrade
- Assuming revision applies changes immediately
4. You run
alembic upgrade head but get an error about missing dependencies in your migration script. What is the best way to fix this?medium
Solution
Step 1: Identify cause of error
Missing dependencies or syntax errors in migration scripts cause upgrade failures.Step 2: Fix the migration script
Editing the script to add missing imports or correct syntax resolves the error and allows upgrade to succeed.Final Answer:
Edit the migration script to add missing imports or fix syntax errors -> Option AQuick Check:
Fix script errors before upgrading [OK]
Hint: Fix migration script errors before upgrading [OK]
Common Mistakes:
- Deleting scripts unnecessarily
- Ignoring errors and retrying blindly
- Downgrading without fixing root cause
5. You want to add a new column to an existing table using Alembic migrations. Which sequence correctly applies this change without losing existing data?
hard
Solution
Step 1: Create a new migration script
Adding a new column requires a new migration script describing the change to preserve history and data.Step 2: Apply the migration
Runningalembic upgrade headapplies the new migration safely without deleting existing data.Final Answer:
Create a new revision script adding the column, then run alembic upgrade head -> Option BQuick Check:
New revision + upgrade = safe schema update [OK]
Hint: Always create new revision for schema changes, then upgrade [OK]
Common Mistakes:
- Modifying old migration scripts after applying
- Deleting database instead of migrating
- Downgrading unnecessarily before adding columns
