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).