Full answer
SQLAlchemy 2.0 (and the current 2.1 line) uses a typed, explicit style.
Setup, once per process:
engine = create_engine(DATABASE_URL, pool_pre_ping=True)
SessionLocal = sessionmaker(engine, expire_on_commit=False)
class Base(DeclarativeBase): pass
class Book(Base):
__tablename__ = "books"
id: Mapped[int] = mapped_column(primary_key=True)
title: Mapped[str] = mapped_column(String(100), index=True)
copies: Mapped[int] = mapped_column(default=1)Session per request:
def get_db():
with SessionLocal() as session:
yield sessionThe with block closes the session (returning the connection to the pool) even when the endpoint raises.
Queries in 2.0 style:
session.get(Book, book_id)for primary key lookup.session.scalars(select(Book).where(Book.copies > 0).order_by(Book.title)).all().session.execute(select(Book.title, func.count()).group_by(...))for rows.- Writes:
session.add(obj),session.commit(),session.refresh(obj);session.delete(obj). - Avoid the legacy
session.query(...)API in new code.
Pydantic integration: response models with model_config = ConfigDict(from_attributes=True) can read ORM objects. expire_on_commit=False keeps attributes loaded after commit so serialisation does not trigger new queries on a closed session.
Production notes:
- Schema changes through Alembic migrations (
alembic revision --autogenerate, review,alembic upgrade head).Base.metadata.create_all()is only for demos and tests. - Tune the pool:
pool_size,max_overflow,pool_pre_ping=True(detects dropped connections),pool_recycle. - Relationship loading: use
selectinload()/joinedload()to avoid N+1 queries when responses include related objects. - Sync SQLAlchemy in
defendpoints runs in the thread pool, which is fine. Forasync defendpoints use the async engine andAsyncSessioninstead. - SQLModel (by FastAPI's author) combines SQLAlchemy models and Pydantic models in one class; useful for simple apps.
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException
from fastapi.testclient import TestClient
from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy import String, create_engine, select
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column, sessionmaker
from sqlalchemy.pool import StaticPool
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
SessionLocal = sessionmaker(engine, expire_on_commit=False)
class Base(DeclarativeBase):
pass
class Book(Base):
__tablename__ = "books"
id: Mapped[int] = mapped_column(primary_key=True)
title: Mapped[str] = mapped_column(String(100), index=True)
copies: Mapped[int] = mapped_column(default=1)
Base.metadata.create_all(engine) # use Alembic migrations in real projects
class BookIn(BaseModel):
title: str = Field(min_length=1, max_length=100)
copies: int = Field(default=1, ge=0)
class BookOut(BookIn):
model_config = ConfigDict(from_attributes=True)
id: int
def get_db():
with SessionLocal() as session:
yield session
DB = Annotated[Session, Depends(get_db)]
app = FastAPI()
@app.post("/books", status_code=201, response_model=BookOut)
def create_book(data: BookIn, db: DB):
book = Book(**data.model_dump())
db.add(book)
db.commit()
return book
@app.get("/books", response_model=list[BookOut])
def list_books(db: DB, available: bool = False):
stmt = select(Book).order_by(Book.title)
if available:
stmt = stmt.where(Book.copies > 0)
return db.scalars(stmt).all()
@app.patch("/books/{book_id}/issue", response_model=BookOut)
def issue(book_id: int, db: DB):
book = db.get(Book, book_id)
if book is None:
raise HTTPException(status_code=404, detail="Book not found")
if book.copies == 0:
raise HTTPException(status_code=409, detail="No copies left")
book.copies -= 1
db.commit()
return book
c = TestClient(app)
print(c.post("/books", json={"title": "Train to Pakistan", "copies": 1}).json())
print(c.post("/books", json={"title": "Godan", "copies": 0}).json())
print(c.patch("/books/1/issue").json())
print(c.patch("/books/1/issue").json(), c.patch("/books/9/issue").status_code)
print([b["title"] for b in c.get("/books").json()], c.get("/books?available=true").json())
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. An in-memory SQLite database with StaticPool keeps the example self-contained; production uses PostgreSQL or MySQL URLs. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'title': 'Train to Pakistan', 'copies': 1, 'id': 1} {'title': 'Godan', 'copies': 0, 'id': 2} {'title': 'Train to Pakistan', 'copies': 0, 'id': 1} {'detail': 'No copies left'} 404 ['Godan', 'Train to Pakistan'] []
Key points
- One engine per process; sessionmaker; session per request
- DeclarativeBase, Mapped, mapped_column for typed models
- 2.0 queries: select(), scalars(), get()
- from_attributes=True and expire_on_commit=False for responses
- Alembic for migrations; eager loading against N+1
Common mistakes
- Creating a new engine per request instead of once per process
- Using the legacy session.query() API in new code
- Forgetting to close sessions, leaking pool connections
- Using sync SQLAlchemy inside async def endpoints and blocking the event loop
- Relying on create_all() instead of Alembic in production
Follow-ups
- How would you avoid N+1 queries when returning books with their authors?
- Why set expire_on_commit=False?
- How do you run Alembic migrations safely during deployment?
Tips
- Show the 2.0 style APIs by name
- Explain session-per-request and why
- Mention Alembic and pool settings for production