agentleFS
ai-enhanced-engineerai-enhanced-engineer/aiee-skills/skills/fastapi-patterns/SKILL.md

fastapi-patterns

Skill4 starsChanged 5 months agoMITView on GitHub

Modern FastAPI 0.111+ production patterns for Python services — async lifespan, Pydantic v2 schemas, dependency injection, middleware ordering, structured exception handlers, router composition. Use for FastAPI endpoint design, service composition, API contract evolution, and migrating from `@app.on_event` / Pydantic v1.

19 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use redis-patterns, typescript-patterns and 10 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • nek1987Skill

    redis-patterns

    Upstash Redis patterns for caching and rate limiting.

    Also in 6 projects that use this

  • cohen-lielSkill

    typescript-patterns

    TypeScript best practices and patterns. Use when writing TypeScript code, defining types, working with generics, or converting JavaScript to TypeScript.

    Also in 3 projects that use this

  • LangChainSkill

    docker-patterns

    Best practices for Docker containerization and multi-stage builds

    Also in 7 projects that use this

  • mstuder-slalomSkill

    golang-patterns

    Idiomatic Go patterns, best practices, and conventions for building robust, efficient, and maintainable Go applications.

    Also in 5 projects that use this

  • mstuder-slalomSkill

    django-security

    Django security best practices, authentication, authorization, CSRF protection, SQL injection prevention, XSS prevention, and secure deployment configurations.

    Also in 4 projects that use this

  • xenitV1Skill

    python-patterns

    Python development principles and decision-making. Framework selection, async patterns, type hints, project structure. Teaches thinking, not copying.

    Also in 6 projects that use this

  • +1 more from mstuder-slalom

The file

Files
SKILL.md

FastAPI Production Patterns

Modern FastAPI 0.111+ patterns for production microservices. This skill covers the patterns that change across versions and trip up teams: lifespan replacing @app.on_event, Pydantic v2 schema patterns, Depends() caching/scoping, middleware LIFO order, and structured error handling.

When to use

  • Designing or refactoring a FastAPI service (new endpoints, lifespan resources, DI graph)
  • Migrating from @app.on_event → lifespan or Pydantic v1 → v2
  • Debugging "CORS missing on 500 errors" or "blocking async endpoint" issues
  • Evolving API contracts (versioning, OpenAPI customization, response schemas)

For modern Python idioms throughout, see arch-python-modern. For service-layer separation (app/routers/ ↔ app/services/ ↔ app/crud/), see arch-ddd.

Core patterns

PatternOne-line rule
Lifespan@asynccontextmanager async def lifespan(app) — startup before yield, shutdown after; reverse-order resource teardown
Depends()Cached once per request; use Annotated[T, Depends(get_x)] aliases at module level
Pydantic v2model_config = ConfigDict(...); @field_validator/@model_validator; model_dump() not .dict()
Schema separationThree classes per resource: XCreate (request), XRead (response), XUpdate (PATCH, all optional)
Middleware orderLIFO — add_middleware last = runs first on request. CORSMiddleware sits outermost so OPTIONS preflight reaches it before auth runs and 500 responses still pass through it (otherwise CORS headers are lost — see reference.md)
Exception handlersRegister @app.exception_handler(Exception) so errors pass through CORS layer (else 500s lose CORS headers)
Router compositionAPIRouter(prefix=..., tags=..., dependencies=[Depends(Auth())]) — apply auth at router, not per-endpoint
Test overridesapp.dependency_overrides[get_db] = fake_db; clearing in fixture teardown prevents cross-test leakage when the app instance persists across tests

Quick reference

# Lifespan (replaces @app.on_event)
@asynccontextmanager
async def lifespan(app: FastAPI):
    create_mongo_client()              # mandatory — let exception abort startup
    await initialize_http_client()
    yield
    shutdown_http_client()              # reverse order
    shutdown_mongo_client()

app = FastAPI(lifespan=lifespan)

# Pydantic v2 schemas
class ProductCreate(BaseModel):
    model_config = ConfigDict(extra="forbid")
    name: str
    sku: str

class ProductRead(BaseModel):
    model_config = ConfigDict(from_attributes=True)
    id: str
    name: str
    sku: str
    created_at: datetime

# Dependency injection (Annotated alias style)
DbSession = Annotated[AsyncSession, Depends(get_db)]

@router.get("/products", response_model=list[ProductRead])
async def list_products(db: DbSession): ...

Anti-patterns (top 4)

  1. Blocking I/O in async def → wrap with await asyncio.to_thread(...) or use httpx.AsyncClient
  2. Mutable default in Depends (tags: list = []) → use None + reassign, or Query(default_factory=list)
  3. Single schema for request + response → split into XCreate / XRead / XUpdate
  4. Missing HTTP client timeouts → httpx.AsyncClient(timeout=httpx.Timeout(connect=2.0, read=5.0))

See reference.md for the full pattern catalogue and examples.md for project-grounded implementations.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.