FastAPI: From Basics to Production · FastAPI Basics
Models, Validation and Dependencies: An Overview
How Pydantic models and dependency injection fit together in FastAPI.
Two ideas power every FastAPI app. Pydantic models describe data: request bodies, responses and settings are validated and converted from type hints. Dependencies (Depends) describe what an endpoint needs — a database session, the current user, pagination parameters — and FastAPI resolves them per request, caching each dependency within a request. Together they keep path functions short and declarative: the signature says what comes in, what's needed and what goes out.
from typing import Annotated
from fastapi import Depends, FastAPI
from pydantic import BaseModel, Field
app = FastAPI()
class Pagination(BaseModel):
limit: int = Field(20, ge=1, le=100)
offset: int = Field(0, ge=0)
async def get_db():
async with SessionLocal() as session:
yield session
DB = Annotated[AsyncSession, Depends(get_db)]
Page = Annotated[Pagination, Depends()]
@app.get("/orders")
async def list_orders(db: DB, page: Page, user: CurrentUser) -> list[OrderOut]:
return await orders.for_user(db, user.id, limit=page.limit, offset=page.offset)
Common pitfalls
- Doing validation manually inside endpoints instead of in models.
- Creating database sessions globally instead of per request.
- Repeating
Depends(...)everywhere instead ofAnnotatedaliases.
Key points
- Models describe data
- Dependencies describe requirements
- Annotated aliases keep signatures clean
Further reading: FastAPI: Dependencies
Practice questions
If two dependencies both depend on get_db, how many sessions are created per request?
Answer
One. FastAPI caches dependency results within a single request by default (use_cache=True), so both receive the same session.
Why define DB = Annotated[AsyncSession, Depends(get_db)]?
Answer
It's a reusable type alias: endpoints just declare db: DB, reducing repetition and keeping the type visible to editors and type checkers.
Open in the app to mark lessons complete, take notes and track your progress.