FastAPI

Project structure, error handling, testing, and deployment guides for FastAPI.

This is how I set up clean and maintainable FastAPI projects: DI, testing, validation, logging, deployment, auth, and more.

Tip

I encourage you to feed the contents of this cookbook into your AI agent of choice. Append raw.md to any page URL to get the raw markdown (e.g. this page’s source would give you the raw markdown of all the pages in this section (concatenated), or the “Source” icon next to any individual page’s title).

What’s inside

Sections are ordered from foundational to advanced:

  1. Project Structure – directory layout, pyproject.toml with uv, app factory pattern
  2. Configurationpydantic-settings, nested settings with prefixes, environment-specific overrides
  3. Dependency Injection – idiomatic DI with Depends, lifespan, app.state, and when to reach for dependency-injector
  4. Validation & Serialization – Pydantic models, custom validators, Annotated field metadata
  5. Error Handling – custom exceptions, problem-detail responses (RFC 9457), validation error reshaping
  6. Testingpytest + httpx.AsyncClient, dependency_overrides, fixtures
  7. Logging – loguru setup, structured JSON output, streaming to CloudWatch
  8. Auth – OAuth2 with JWT, security schemes via Depends, role-based access
  9. Deployment – multi-stage Dockerfile, uvicorn production settings, health checks

Project Structure

How to lay out a FastAPI project so it stays maintainable as it grows. ...

2026-03-18

Configuration

Managing application settings with pydantic-settings — type-safe, validated, and environment-aware. ...

2026-03-18

Dependency Injection

Patterns for wiring settings, repositories, services, DB pools, and per-request objects into FastAPI route handlers — using only what the framework gives you. ...

2026-03-18

Error Handling

Turning exceptions into consistent, machine-readable API responses. ...

2026-03-18

Testing

Testing FastAPI apps with pytest, httpx.AsyncClient, and pytest-asyncio. For project setup (pyproject.toml, test directory layout, asyncio_mode), see Project Structure. ...

2026-03-18

Logging

Setting up logging for a FastAPI application (or any other Python application, for that matter). ...

2026-03-18

Auth

Authentication and authorization patterns for FastAPI. ...

2026-03-18

Deployment

Getting a FastAPI app into production. ...