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")
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
