0
0
FastAPIframework~30 mins

Alembic migrations in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
Alembic Migrations with FastAPI
📖 Scenario: You are building a simple FastAPI app to manage books in a library. You want to keep track of your database changes safely using Alembic migrations.
🎯 Goal: Create a basic Alembic migration setup for a FastAPI project. Define an initial database model, configure Alembic, generate a migration script, and apply it to create the database table.
📋 What You'll Learn
Create a SQLAlchemy model for a Book with id and title fields
Set up Alembic configuration with the correct database URL
Generate an Alembic migration script for the Book model
Apply the migration to create the books table in the database
💡 Why This Matters
🌍 Real World
Alembic migrations help developers safely update database schemas as their applications grow and change.
💼 Career
Understanding Alembic migrations is essential for backend developers working with FastAPI and SQLAlchemy to maintain database integrity.
Progress0 / 4 steps
1
Create the SQLAlchemy Book model
Create a SQLAlchemy model class called Book with a table name books. It should have two columns: id as an integer primary key and title as a string of max length 100.
FastAPI
Need a hint?

Use class Book(Base): and set __tablename__ = 'books'. Define id and title columns with correct types.

2
Configure Alembic with the database URL
Add a variable called SQLALCHEMY_DATABASE_URL and set it to sqlite:///./test.db. This will be the database URL Alembic uses.
FastAPI
Need a hint?

Set SQLALCHEMY_DATABASE_URL exactly to "sqlite:///./test.db".

3
Generate Alembic migration script
Write a command string variable called alembic_command with the value "alembic revision --autogenerate -m 'create books table'". This command generates the migration script for the Book model.
FastAPI
Need a hint?

Set alembic_command to the exact Alembic command string to generate migration.

4
Apply Alembic migration to create the table
Write a command string variable called alembic_upgrade with the value "alembic upgrade head". This command applies the migration and creates the books table in the database.
FastAPI
Need a hint?

Set alembic_upgrade to the exact Alembic command string to apply migration.