Skip to content
Goal: Deep understanding✓ Sources verified 2026-11-24Dependsyield DependenciesPydantic v2Middleware

FastAPI: Dependency Injection, Pydantic v2 and Project Layering ​

Core concepts ​

ConceptRole
DependsDeclares a dependency (a function or class); FastAPI calls it and injects the result. Dependencies can depend on other dependencies
yield dependenciesCode before yield is setup (e.g. opening a DB session), code after it is cleanup (close / roll back). Good for resource management
Annotated styleOfficially recommended: db: Annotated[Session, Depends(get_db)], reusable as a type alias
Pydantic v2Request body validation, response serialization, settings management. The core was rewritten in Rust (pydantic-core) and is much faster than v1
MiddlewareWraps every request: trace_id, timing, CORS
Exception handlers@app.exception_handler(MyError) turns business exceptions into consistent error codes
lifespanInitialize 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 yield dependencies.
  • Common Pydantic v2 APIs (renamed from v1): model_validate() (was parse_obj), model_dump() (was dict()), model_validate_json(), model_json_schema(), @field_validator / @model_validator (were @validator / @root_validator), model_config = ConfigDict(...) (was the inner class 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 variables

Managing 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 ​

  1. Doing business work in a yield dependency's cleanup phase: when that phase runs has changed across FastAPI versions. Only release resources there.
  2. Creating a new HTTP client / LLM client per request: connections can't be reused. Create them once in lifespan.
  3. Mixing in Pydantic v1 style: .dict() and parse_obj are deprecated in v2.
  4. Response models leaking fields: use a separate XxxOut model so fields like password hashes never reach the frontend.

Common interview questions ​

  1. How does FastAPI dependency injection work? How many times does a dependency run within one request?
  2. What are yield dependencies good for? When does the cleanup code run?
  3. In what order do middleware, dependencies and exception handlers run?
  4. What changed in Pydantic v2 compared with v1?
  5. How is your FastAPI project layered, and why?

To be verified / may go stale

  • When a yield dependency'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.

Sources ​

Vin Amory · AI development × content creation · Technical notes cite official docs in each page’s sources section