Project Structure
How to lay out a FastAPI project so it stays maintainable as it grows. ...
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.mdto 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).
Sections are ordered from foundational to advanced:
pyproject.toml with uv, app factory patternpydantic-settings, nested settings with prefixes, environment-specific overridesDepends, lifespan, app.state, and when to reach for dependency-injectorAnnotated field metadatapytest + httpx.AsyncClient, dependency_overrides, fixturesDepends, role-based accessuvicorn production settings, health checksHow to lay out a FastAPI project so it stays maintainable as it grows. ...
Managing application settings with pydantic-settings — type-safe, validated, and environment-aware. ...
Patterns for wiring settings, repositories, services, DB pools, and per-request objects into FastAPI route handlers — using only what the framework gives you. ...
Using Pydantic to validate incoming data and shape outgoing responses. ...
Turning exceptions into consistent, machine-readable API responses. ...
Testing FastAPI apps with pytest, httpx.AsyncClient, and pytest-asyncio. For project setup (pyproject.toml, test directory layout, asyncio_mode), see Project Structure. ...
Setting up logging for a FastAPI application (or any other Python application, for that matter). ...
Authentication and authorization patterns for FastAPI. ...
Getting a FastAPI app into production. ...