What is Alembic and how does it work with FastAPI?
Answer
Alembic is the database migration tool for SQLAlchemy. With FastAPI, use it directly (unlike Flask-Migrate which wraps it). Setup: pip install alembic; alembic init alembic. Configure alembic.ini with the database URL. Edit alembic/env.py to import your SQLAlchemy Base and metadata: from app.models import Base; target_metadata = Base.metadata. Commands: alembic revision --autogenerate -m "Add users table" (generate migration), alembic upgrade head (apply all migrations), alembic downgrade -1 (roll back one). Run migrations in the Docker entrypoint or app startup (use caution with multiple instances — only one should run migrations). Store migrations in version control. For async SQLAlchemy, configure Alembic to run migrations synchronously (connections in env.py use the sync engine for migrations even if the app uses async).
Previous
How do you implement middleware in FastAPI?
Next
How do you write tests for Flask and FastAPI applications?
More FastAPI / Flask Questions
View all →- Intermediate How do you implement JWT authentication in FastAPI?
- Intermediate How does SQLAlchemy async work with FastAPI?
- Intermediate What is Flask's application factory pattern?
- Intermediate How do you implement background tasks in FastAPI?
- Intermediate What is Pydantic v2 and what changed from v1?