FastAPI: Dependency Injection, Pydantic v2 and Project Layering
Core concepts
| Concept | Role |
|---|---|
Depends | Declares a dependency (a function or class); FastAPI calls it and injects the result. Dependencies can depend on other dependencies |
yield dependencies | Code before yield is setup (e.g. opening a DB session), code after it is cleanup (close / roll back). Good for resource management |
Annotated style | Officially recommended: db: Annotated[Session, Depends(get_db)], reusable as a type alias |
| Pydantic v2 | Request body validation, response serialization, settings management. The core was rewritten in Rust (pydantic-core) and is much faster than v1 |
| Middleware | Wraps every request: trace_id, timing, CORS |
| Exception handlers | @app.exception_handler(MyError) turns business exceptions into consistent error codes |
lifespan | Initialize and release resources at app startup / shutdown (connection pools, HTTP clients) |
How it works
- Dependencies are cached within a request by default: if several places use
Depends(get_db), it's called only once per request (use_cache=True). - Execution order: request → middleware (outer layer) → route matching → parse parameters / run dependencies → route function → response → cleanup code of
yielddependencies. - Common Pydantic v2 APIs (renamed from v1):
model_validate()(wasparse_obj),model_dump()(wasdict()),model_validate_json(),model_json_schema(),@field_validator/@model_validator(were@validator/@root_validator),model_config = ConfigDict(...)(was the innerclass Config).
In practice
Layered structure
app/
main.py # create the app, lifespan, middleware, exception handlers
api/routes/ # routers: only parse parameters and call services
services/ # business logic: orchestration, calls to the LLM Gateway
repositories/ # data access
schemas/ # Pydantic models (request / response / LLM output)
core/config.py # pydantic-settings reads environment variablesManaging the database session with a yield dependency
python
from typing import Annotated
from collections.abc import AsyncIterator
from fastapi import Depends
from sqlalchemy.ext.asyncio import AsyncSession
async def get_db() -> AsyncIterator[AsyncSession]:
async with SessionLocal() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
DB = Annotated[AsyncSession, Depends(get_db)]
@router.post("/tasks")
async def create_task(body: TaskCreate, db: DB, user: CurrentUser) -> TaskOut:
return await task_service.create(db, user, body)Consistent error codes
python
class BizError(Exception):
def __init__(self, code: str, msg: str, status: int = 400):
self.code, self.msg, self.status = code, msg, status
@app.exception_handler(BizError)
async def biz_error_handler(request, exc: BizError):
return JSONResponse(status_code=exc.status,
content={"code": exc.code, "message": exc.msg, "trace_id": request.state.trace_id})Common pitfalls
- Doing business work in a yield dependency's cleanup phase: when that phase runs has changed across FastAPI versions. Only release resources there.
- Creating a new HTTP client / LLM client per request: connections can't be reused. Create them once in
lifespan. - Mixing in Pydantic v1 style:
.dict()andparse_objare deprecated in v2. - Response models leaking fields: use a separate
XxxOutmodel so fields like password hashes never reach the frontend.
Common interview questions
- How does FastAPI dependency injection work? How many times does a dependency run within one request?
- What are
yielddependencies good for? When does the cleanup code run? - In what order do middleware, dependencies and exception handlers run?
- What changed in Pydantic v2 compared with v1?
- How is your FastAPI project layered, and why?
To be verified / may go stale
- When a
yielddependency's exit code runs relative to sending the response has changed in past FastAPI versions (e.g. the 0.106.0 change). Check the Release Notes of your current version before relying on this behavior.
