Search Topics
Search across all FastAPI topics
Database
4 topicsThe complete database workflow for FastAPI — define models with SQLAlchemy, manage sessions with dependency injection, version your schema with Alembic, and build clean CRUD operations.
Tip
FastAPI pairs naturally with SQLAlchemy for ORM, Alembic for migrations, and dependency injection for session management. Together they form a complete, production-ready database layer.
The Database Workflow
Step 1: Define Models
Create Python classes that map to database tables using SQLAlchemy ORM.
SQLAlchemy Models
Define tables, column types, and relationships using SQLAlchemy ORM.
Database Sessions
Engine setup, SessionLocal, and the get_db() yield dependency pattern.
Alembic Migrations
Version control your database schema with autogenerated migrations.
CRUD Operations
Repository pattern for create, read, update, delete with SQLAlchemy.
These are the patterns that trip up developers most often. Switch between Wrong and Fixed to compare the code side by side.
1
Not closing database sessions
Creating sessions without cleanup
Don't do this
main.py
@app.get("/users")
def list_users():
db = SessionLocal() # Session created
users = db.query(User).all()
return users
# Session never closed — connection leaks!Always use the get_db() dependency with yield/finally to ensure sessions are closed. Creating sessions manually without cleanup leaks database connections under load.
2
Using create_all() in production
Skipping migrations for convenience
Don't do this
main.py
# main.py — DON'T do this in production
from database import Base, engine
Base.metadata.create_all(bind=engine) # ← Only creates
# Can't track changes, can't rollback, no migration historycreate_all() only creates tables that don't exist — it can't alter existing tables. Use Alembic migrations for production to track schema changes, support rollbacks, and maintain a version history.