FastAPI Patterns
Patterns and conventions for building FastAPI applications. Follow the principle of
explicit dependency injection, leverage async where it matters, and use Pydantic models
as the single source of truth for request/response schemas.
Core Principles
- Dependency injection everywhere -- Use
Depends() for database sessions, auth,
config, and shared logic instead of global state or imports
- Pydantic as contract -- Define request and response models explicitly with Pydantic;
avoid raw dicts in route signatures
- Async when beneficial -- Use
async def for I/O-bound routes with async drivers;
use plain def for CPU-bound or sync-only code
- Router organization -- Split routes into
APIRouter modules by domain, compose them
in the main app with prefixes and tags
When to Use
Apply these patterns when working on any project that lists fastapi in its dependencies.
Detect this by checking pyproject.toml, requirements.txt, or Pipfile for FastAPI.
Type Hints
Use | None instead of Optional for all type annotations:
from fastapi import Query
async def list_items(
category: str | None = Query(None, description="Filter by category"),
) -> list[ItemResponse]:
...
Logging
Use emojis as prefixes in log messages:
logger.info("✅ Request processed for %s", endpoint)
logger.warning("⚠️ Rate limit approaching for client %s", client_id)
logger.error("❌ Failed to connect to database: %s", exc)
Project Structure
src/
├── main.py # App factory, lifespan, router composition
├── config.py # Settings with pydantic-settings
├── dependencies.py # Shared dependencies (DB session, current user)
├── routes/
│ ├── __init__.py
│ ├── users.py # APIRouter for user endpoints
│ └── items.py # APIRouter for item endpoints
├── models/ # SQLAlchemy or ORM models
├── schemas/ # Pydantic request/response models
├── services/ # Business logic layer
└── middleware/ # Custom middleware
Reference Documents
- routes-di.md -- Routes, dependency injection, middleware,
error handling, OpenAPI customization, lifespan events
- async-patterns.md -- Async/await patterns, background
tasks, WebSockets, streaming, connection pooling, testing
- auth.md -- Authentication and authorization: OAuth2, JWT, API
keys, RBAC, scopes, password hashing, CORS for auth
Source: weorbitant/compound-engineering-feat-python-plugin — distributed by TomeVault.
1---2name: fastapi-patterns-153description: FastAPI core patterns for routes, dependency injection, async, auth, and OpenAPI. Use when working on projects with fastapi in their dependencies. Use when this capability is needed.4---56# FastAPI Patterns78Patterns and conventions for building FastAPI applications. Follow the principle of9explicit dependency injection, leverage async where it matters, and use Pydantic models10as the single source of truth for request/response schemas.1112## Core Principles1314- **Dependency injection everywhere** -- Use `Depends()` for database sessions, auth,15 config, and shared logic instead of global state or imports16- **Pydantic as contract** -- Define request and response models explicitly with Pydantic;17 avoid raw dicts in route signatures18- **Async when beneficial** -- Use `async def` for I/O-bound routes with async drivers;19 use plain `def` for CPU-bound or sync-only code20- **Router organization** -- Split routes into `APIRouter` modules by domain, compose them21 in the main app with prefixes and tags2223## When to Use2425Apply these patterns when working on any project that lists `fastapi` in its dependencies.26Detect this by checking `pyproject.toml`, `requirements.txt`, or `Pipfile` for FastAPI.2728## Type Hints2930Use `| None` instead of `Optional` for all type annotations:3132```python33from fastapi import Query3435async def list_items(36 category: str | None = Query(None, description="Filter by category"),37) -> list[ItemResponse]:38 ...39```4041## Logging4243Use emojis as prefixes in log messages:4445```python46logger.info("✅ Request processed for %s", endpoint)47logger.warning("⚠️ Rate limit approaching for client %s", client_id)48logger.error("❌ Failed to connect to database: %s", exc)49```5051## Project Structure5253```54src/55├── main.py # App factory, lifespan, router composition56├── config.py # Settings with pydantic-settings57├── dependencies.py # Shared dependencies (DB session, current user)58├── routes/59│ ├── __init__.py60│ ├── users.py # APIRouter for user endpoints61│ └── items.py # APIRouter for item endpoints62├── models/ # SQLAlchemy or ORM models63├── schemas/ # Pydantic request/response models64├── services/ # Business logic layer65└── middleware/ # Custom middleware66```6768## Reference Documents6970- [routes-di.md](./references/routes-di.md) -- Routes, dependency injection, middleware,71 error handling, OpenAPI customization, lifespan events72- [async-patterns.md](./references/async-patterns.md) -- Async/await patterns, background73 tasks, WebSockets, streaming, connection pooling, testing74- [auth.md](./references/auth.md) -- Authentication and authorization: OAuth2, JWT, API75 keys, RBAC, scopes, password hashing, CORS for auth7677---78> Source: [weorbitant/compound-engineering-feat-python-plugin](https://github.com/weorbitant/compound-engineering-feat-python-plugin) — distributed by [TomeVault](https://tomevault.io).79<!-- tomevault:4.0:skill_md:2026-06-15 -->