Python / FastAPI Basics Interview Questions
How do you manage database schema migrations in a FastAPI project with Alembic?
Alembic is the standard database migration tool for SQLAlchemy. It tracks schema changes as versioned migration scripts that can be applied or rolled back. This is essential for production databases — never rely solely on create_all().
# 1. Install and initialise Alembic # pip install alembic # alembic init alembic # This creates alembic/ directory and alembic.ini
# alembic/env.py â point to your models and database from app.database import Base, DATABASE_URL # your app imports from app import models # noqa: import models so Alembic can see them # In run_migrations_online(): connectable = create_engine(DATABASE_URL) # Set target_metadata so Alembic compares your models vs the DB target_metadata = Base.metadata
# 2. Generate a migration after changing a model alembic revision --autogenerate -m "add users table" # Creates alembic/versions/xxxx_add_users_table.py # 3. Apply migrations alembic upgrade head # apply all pending migrations alembic upgrade +1 # apply one migration # 4. Rollback alembic downgrade -1 # undo one migration alembic downgrade base # undo ALL migrations # 5. View history alembic history # list all migrations alembic current # show current DB revision
# Generated migration file â always review before applying! def upgrade() -> None: op.create_table( "users", sa.Column("id", sa.Integer(), primary_key=True), sa.Column("username", sa.String(), nullable=False), sa.Column("email", sa.String(), nullable=False), ) def downgrade() -> None: op.drop_table("users")
More Related questions...