Providing comprehensive FastAPI CQRS boilerplate with Alembic migration check
The plan is to deliver a full FastAPI project structure implementing CQRS with separate read/write models, async SQLAlchemy, Pydantic schemas, an example command/handler pattern, and Alembic migrations. Crucially, it includes a pre-commit hook script that detects any model changes unaccompanied by migrations using Alembic's autogenerate API, failing if pending migrations exist. The provided code and config ensure a solid starting point for development with enforced migration discipline.
Below is a minimal FastAPI + SQLAlchemy 2.0 CQRS boilerplate, with Alembic migrations and a pre-commit hook that fails if your SQLAlchemy models differ from the latest applied migration.
Directory layout (one possible variant):
.
├── alembic.ini
├── alembic/
│ ├── env.py
│ └── versions/
├── app/
│ ├── __init__.py
│ ├── main.py
│ ├── config.py
│ ├── db.py
│ ├── domain/
│ │ ├── __init__.py
│ │ └── models.py
│ ├── cqrs/
│ │ ├── __init__.py
│ │ ├── commands.py
│ │ ├── handlers.py
│ │ ├── queries.py
│ │ └── query_handlers.py
│ ├── api/
│ │ ├── __init__.py
│ │ └── routes.py
│ └── schemas.py
├── scripts/
│ └── check_migrations.py
├── .pre-commit-config.yaml
├── pyproject.toml
└── README.md
pyproject.toml (deps)
[build-system]
requires = ["setuptools", "wheel"]
[project]
name = "fastapi-cqrs-alembic-boilerplate"
version = "0.1.0"
dependencies = [
"fastapi>=0.109",
"uvicorn[standard]>=0.23",
"pydantic>=2",
"SQLAlchemy>=2",
"alembic>=1.12",
"psycopg2-binary>=2.9", # or asyncpg if you go async-postgres
"python-dotenv>=1.0",
]
app/config.py
import os
from pydantic import BaseSettings, PostgresDsn, Field
class Settings(BaseSettings):
database_url: PostgresDsn = Field(..., env="DATABASE_URL")
# If you want async, supply something like: postgresql+asyncpg://user:pass@localhost:5432/dbname
app_name: str = "cqrs-example"
class Config:
env_file = ".env"
settings = Settings()
app/db.py
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
from sqlalchemy.orm import DeclarativeBase
from app.config import settings
class Base(DeclarativeBase):
pass
engine = create_async_engine(settings.database_url, future=True, echo=False)
AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False)
async def get_write_session() -> AsyncSession:
async with AsyncSessionLocal() as session:
yield session
async def get_read_session() -> AsyncSession:
"""
In a real CQRS setup, this could point to a read replica or a different store.
Here we reuse the same DB for demo purposes.
"""
async with AsyncSessionLocal() as session:
yield session
app/domain/models.py (write models)
from sqlalchemy import String
from sqlalchemy.orm import Mapped, mapped_column
from app.db import Base
class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
email: Mapped[str] = mapped_column(String(255), unique=True, nullable=False)
full_name: Mapped[str] = mapped_column(String(255), nullable=False)
app/schemas.py (command payloads + read models)
from pydantic import BaseModel, EmailStr, constr
class CreateUserIn(BaseModel):
email: EmailStr
full_name: constr(min_length=1)
class UserReadModel(BaseModel):
id: int
email: EmailStr
full_name: str
class Config:
from_attributes = True # allow ORM -> pydantic
app/cqrs/commands.py
from dataclasses import dataclass
@dataclass
class CreateUserCommand:
email: str
full_name: str
app/cqrs/handlers.py (write side)
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.exc import IntegrityError
from app.cqrs.commands import CreateUserCommand
from app.domain.models import User
class CommandHandlerError(Exception):
...
class CreateUserHandler:
async def __call__(self, cmd: CreateUserCommand, session: AsyncSession) -> User:
user = User(email=cmd.email, full_name=cmd.full_name)
session.add(user)
try:
await session.commit()
await session.refresh(user)
except IntegrityError as e:
await session.rollback()
raise CommandHandlerError(f"User with email {cmd.email} already exists.") from e
return user
app/cqrs/queries.py
from dataclasses import dataclass
@dataclass
class GetUserByIdQuery:
user_id: int
app/cqrs/query_handlers.py (read side)
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from fastapi import HTTPException
from app.cqrs.queries import GetUserByIdQuery
from app.domain.models import User
from app.schemas import UserReadModel
class GetUserByIdHandler:
async def __call__(self, qry: GetUserByIdQuery, session: AsyncSession) -> UserReadModel:
stmt = select(User).where(User.id == qry.user_id)
result = await session.execute(stmt)
user = result.scalar_one_or_none()
if not user:
raise HTTPException(status_code=404, detail="User not found")
return UserReadModel.model_validate(user)
app/api/routes.py
from fastapi import APIRouter, Depends
from app.schemas import CreateUserIn, UserReadModel
from app.cqrs.commands import CreateUserCommand
from app.cqrs.handlers import CreateUserHandler
from app.cqrs.queries import GetUserByIdQuery
from app.cqrs.query_handlers import GetUserByIdHandler
from app.db import get_write_session, get_read_session
from sqlalchemy.ext.asyncio import AsyncSession
router = APIRouter(prefix="/users", tags=["users"])
@router.post("", response_model=UserReadModel, status_code=201)
async def create_user(
payload: CreateUserIn,
session: AsyncSession = Depends(get_write_session),
):
handler = CreateUserHandler()
user = await handler(
CreateUserCommand(email=payload.email, full_name=payload.full_name),
session,
)
return UserReadModel.model_validate(user)
@router.get("/{user_id}", response_model=UserReadModel)
async def get_user(
user_id: int,
session: AsyncSession = Depends(get_read_session),
):
handler = GetUserByIdHandler()
return await handler(GetUserByIdQuery(user_id=user_id), session)
app/main.py
from fastapi import FastAPI
from app.api.routes import router as user_router
app = FastAPI(title="CQRS Example")
app.include_router(user_router)
# If you want to run with: uvicorn app.main:app --reload
Alembic setup
alembic.ini (minimal)
[alembic]
script_location = alembic
sqlalchemy.url = postgresql://user:password@localhost:5432/yourdb # overridden in env.py if needed
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
[logger_sqlalchemy]
level = WARN
handlers = console
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers = console
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stdout,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
alembic/env.py (async variant)
from logging.config import fileConfig
from sqlalchemy import pool
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import async_engine_from_config
from alembic import context
from app.db import Base
from app.config import settings
# this is the Alembic Config object, which provides access to values
config = context.config
# interpret the config file for Python logging.
if config.config_file_name is not None:
fileConfig(config.config_file_name)
target_metadata = Base.metadata
def run_migrations_online() -> None:
connectable = async_engine_from_config(
config.get_section(config.config_ini_section),
prefix="sqlalchemy.",
url=settings.database_url,
poolclass=pool.NullPool,
)
async def do_run_migrations(connection: Connection):
context.configure(
connection=connection,
target_metadata=target_metadata,
compare_type=True,
compare_server_default=True,
)
with context.begin_transaction():
context.run_migrations()
import asyncio
asyncio.run(
connectable.run_sync(do_run_migrations)
)
run_migrations_online()
Create your first migration:
alembic revision --autogenerate -m "create users"
alembic upgrade head
Pre-commit hook to enforce migrations
We add a local hook that autogenerates a diff in memory and fails if any changes are detected (i.e., if your models differ from what’s in the DB at HEAD). Important: your local DB must be migrated to head before committing, otherwise the check will correctly fail.
scripts/check_migrations.py
#!/usr/bin/env python
"""
Fails if SQLAlchemy models differ from the current database schema (i.e., pending migration).
Make sure your DB is migrated to head before running.
"""
import sys
from alembic.autogenerate import compare_metadata
from alembic.migration import MigrationContext
from sqlalchemy import create_engine
from sqlalchemy.engine.reflection import Inspector
from app.config import settings
from app.db import Base
def main() -> int:
# Use a SYNC URL for autogenerate diff; if using async driver, supply a sync URL as well.
url = settings.database_url
sync_url = url.replace("+asyncpg", "") if "+asyncpg" in url else url
engine = create_engine(sync_url)
with engine.connect() as conn:
# Ensure schemas are loaded if needed
ctx = MigrationContext.configure(
conn,
opts={
"target_metadata": Base.metadata,
"compare_type": True,
"compare_server_default": True,
"include_schemas": True,
},
)
diffs = compare_metadata(ctx, Base.metadata)
if diffs:
print("❌ Pending model changes detected! Create an Alembic migration.")
for diff in diffs:
print(f" - {diff}")
return 1
print("✅ No pending model changes detected.")
return 0
if __name__ == "__main__":
sys.exit(main())
Make it executable:
chmod +x scripts/check_migrations.py
.pre-commit-config.yaml
repos:
- repo: https://github.com/psf/black
rev: 24.1.1
hooks:
- id: black
- repo: https://github.com/PyCQA/isort
rev: 5.12.0
hooks:
- id: isort
- repo: local
hooks:
- id: alembic-migration-check
name: Ensure DB models match migrations (no pending autogenerate diff)
entry: python scripts/check_migrations.py
language: system
types: [python]
pass_filenames: false
Install the hooks:
pre-commit install
Now any commit will fail if scripts/check_migrations.py detects a schema diff (i.e., you changed ORM models without creating a migration).
Running the app
- Set
DATABASE_URL in .env (example: postgresql+asyncpg://user:password@localhost:5432/mydb).
- Run migrations:
alembic upgrade head.
- Start the app:
uvicorn app.main:app --reload.
- Test:
POST /users with { "email": "...", "full_name": "..." }
GET /users/{id}
This is a small but complete CQRS-style skeleton: write operations go through command handlers (mutate write model), and read operations go through query handlers returning read models. Alembic manages schema, and pre-commit guards against un-migrated model changes.