Search Topics

Search across all FastAPI topics

GitHub

Database

4 topics

The 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.

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 history
create_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.