fastapi-patterns

Build production FastAPI applications with dependency injection, middleware, background tasks, and structured project layouts. Covers async patterns, Pydantic models, OpenAPI customization, and testing strategies. Triggers on FastAPI development, Python API, or async web framework requests.

Best use case

fastapi-patterns is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Build production FastAPI applications with dependency injection, middleware, background tasks, and structured project layouts. Covers async patterns, Pydantic models, OpenAPI customization, and testing strategies. Triggers on FastAPI development, Python API, or async web framework requests.

Teams using fastapi-patterns should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/fastapi-patterns/SKILL.md --create-dirs "https://raw.githubusercontent.com/organvm-iv-taxis/a-i--skills/main/distributions/claude/skills/fastapi-patterns/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/fastapi-patterns/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How fastapi-patterns Compares

Feature / Agentfastapi-patternsStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Build production FastAPI applications with dependency injection, middleware, background tasks, and structured project layouts. Covers async patterns, Pydantic models, OpenAPI customization, and testing strategies. Triggers on FastAPI development, Python API, or async web framework requests.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# FastAPI Patterns

Build production-ready async APIs with FastAPI's dependency injection and type system.

## Project Layout

```
src/
├── app/
│   ├── __init__.py
│   ├── main.py           # FastAPI app factory
│   ├── config.py          # Pydantic Settings
│   ├── dependencies.py    # Shared DI providers
│   ├── middleware.py       # Custom middleware
│   ├── routers/
│   │   ├── __init__.py
│   │   ├── skills.py
│   │   └── registry.py
│   ├── models/
│   │   ├── __init__.py
│   │   ├── skill.py       # Pydantic models
│   │   └── registry.py
│   ├── services/
│   │   ├── __init__.py
│   │   ├── skill_service.py
│   │   └── registry_service.py
│   └── db/
│       ├── __init__.py
│       └── session.py
└── tests/
    ├── conftest.py
    └── test_skills.py
```

## App Factory

```python
from fastapi import FastAPI
from contextlib import asynccontextmanager

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup
    await init_db()
    await init_cache()
    yield
    # Shutdown
    await close_db()
    await close_cache()

def create_app() -> FastAPI:
    app = FastAPI(
        title="ORGANVM Skills API",
        version="1.0.0",
        lifespan=lifespan,
    )
    app.include_router(skills_router, prefix="/api/skills", tags=["skills"])
    app.include_router(registry_router, prefix="/api/registry", tags=["registry"])
    app.add_middleware(CorrelationMiddleware)
    return app

app = create_app()
```

## Dependency Injection

```python
from fastapi import Depends
from typing import Annotated

async def get_db():
    async with async_session() as session:
        yield session

async def get_current_user(token: str = Depends(oauth2_scheme)) -> User:  # allow-secret
    user = await verify_token(token)
    if not user:
        raise HTTPException(status_code=401, detail="Invalid token")
    return user

# Type aliases for clean signatures
DB = Annotated[AsyncSession, Depends(get_db)]
CurrentUser = Annotated[User, Depends(get_current_user)]

@router.get("/skills/{skill_id}")
async def get_skill(skill_id: str, db: DB, user: CurrentUser) -> SkillResponse:
    skill = await db.get(Skill, skill_id)
    if not skill:
        raise HTTPException(status_code=404, detail="Skill not found")
    return SkillResponse.model_validate(skill)
```

## Pydantic Models

```python
from pydantic import BaseModel, Field
from datetime import datetime

class SkillBase(BaseModel):
    name: str = Field(pattern=r"^[a-z][a-z0-9-]*$", min_length=2, max_length=64)
    description: str = Field(min_length=20, max_length=600)
    category: str
    tags: list[str] = []

class SkillCreate(SkillBase):
    pass

class SkillResponse(SkillBase):
    id: str
    created_at: datetime
    updated_at: datetime

    model_config = {"from_attributes": True}

class SkillList(BaseModel):
    items: list[SkillResponse]
    total: int
    page: int
    per_page: int
```

## Router Patterns

```python
from fastapi import APIRouter, Query

router = APIRouter()

@router.get("/", response_model=SkillList)
async def list_skills(
    db: DB,
    category: str | None = None,
    tag: str | None = None,
    page: int = Query(default=1, ge=1),
    per_page: int = Query(default=20, ge=1, le=100),
) -> SkillList:
    query = select(Skill)
    if category:
        query = query.where(Skill.category == category)
    if tag:
        query = query.where(Skill.tags.contains([tag]))
    total = await db.scalar(select(func.count()).select_from(query.subquery()))
    skills = await db.scalars(query.offset((page - 1) * per_page).limit(per_page))
    return SkillList(items=skills.all(), total=total, page=page, per_page=per_page)

@router.post("/", response_model=SkillResponse, status_code=201)
async def create_skill(data: SkillCreate, db: DB, user: CurrentUser) -> SkillResponse:
    skill = Skill(**data.model_dump())
    db.add(skill)
    await db.commit()
    await db.refresh(skill)
    return SkillResponse.model_validate(skill)
```

## Background Tasks

```python
from fastapi import BackgroundTasks

@router.post("/skills/{skill_id}/validate")
async def validate_skill(
    skill_id: str,
    background_tasks: BackgroundTasks,
    db: DB,
):
    skill = await db.get(Skill, skill_id)
    background_tasks.add_task(run_validation, skill_id)
    return {"status": "validation_queued", "skill_id": skill_id}

async def run_validation(skill_id: str):
    # Long-running validation logic
    async with async_session() as db:
        skill = await db.get(Skill, skill_id)
        result = await validate_frontmatter(skill)
        skill.validation_status = result.status
        await db.commit()
```

## Error Handling

```python
from fastapi import Request
from fastapi.responses import JSONResponse

class AppError(Exception):
    def __init__(self, message: str, code: str, status: int):
        self.message = message
        self.code = code
        self.status = status

@app.exception_handler(AppError)
async def app_error_handler(request: Request, exc: AppError):
    return JSONResponse(
        status_code=exc.status,
        content={"error": {"code": exc.code, "message": exc.message}},
    )
```

## Testing

```python
import pytest
from httpx import AsyncClient, ASGITransport

@pytest.fixture
async def client():
    async with AsyncClient(
        transport=ASGITransport(app=app),
        base_url="http://test",
    ) as client:
        yield client

@pytest.mark.asyncio
async def test_list_skills(client: AsyncClient):
    response = await client.get("/api/skills/")
    assert response.status_code == 200
    data = response.json()
    assert "items" in data
    assert "total" in data

@pytest.mark.asyncio
async def test_create_skill(client: AsyncClient):
    response = await client.post("/api/skills/", json={
        "name": "test-skill",
        "description": "A test skill for unit testing purposes",
        "category": "development",
    })
    assert response.status_code == 201
    assert response.json()["name"] == "test-skill"
```

## Anti-Patterns

- **Sync database calls** — Always use async drivers (asyncpg, aiosqlite)
- **Business logic in routes** — Extract to service layer for testability
- **No response models** — Always define response_model for API documentation
- **Global state** — Use dependency injection, not module-level singletons
- **Missing validation** — Pydantic models should validate all inputs
- **No lifespan management** — Use the lifespan context manager for startup/shutdown

Related Skills

webhook-integration-patterns

5
from organvm-iv-taxis/a-i--skills

Designs reliable webhook systems with proper delivery guarantees, retry logic, signature verification, and idempotent processing for event-driven integrations.

vector-search-patterns

5
from organvm-iv-taxis/a-i--skills

Implement vector similarity search with embedding generation, index selection, and hybrid retrieval strategies. Covers ChromaDB, pgvector, FAISS, and RAG pipeline design. Triggers on vector search, embeddings, semantic search, or RAG architecture requests.

testing-patterns

5
from organvm-iv-taxis/a-i--skills

Write effective tests across the stack—unit, integration, E2E, and visual regression. Covers testing philosophy, framework selection, mocking strategies, and CI integration. Triggers on testing, test coverage, TDD, or quality assurance requests.

session-lifecycle-patterns

5
from organvm-iv-taxis/a-i--skills

Manage AI agent session lifecycles with structured phases (FRAME, SHAPE, BUILD, PROVE), context preservation across sessions, handoff protocols, and session metadata tracking. Triggers on session management, agent lifecycle, or multi-session workflow requests.

responsive-design-patterns

5
from organvm-iv-taxis/a-i--skills

Mobile-first responsive design patterns with breakpoints, fluid layouts, and adaptive components

resilience-patterns

5
from organvm-iv-taxis/a-i--skills

Build fault-tolerant systems with circuit breakers, retries with backoff, bulkheads, timeouts, and graceful degradation. Covers distributed system failure modes and recovery strategies. Triggers on reliability engineering, fault tolerance, or distributed system resilience requests.

redis-patterns

5
from organvm-iv-taxis/a-i--skills

Use Redis effectively for caching, pub/sub messaging, rate limiting, distributed locks, and session storage. Covers data structure selection, expiration strategies, and cluster patterns. Triggers on Redis usage, caching architecture, or pub/sub messaging requests.

realtime-websocket-patterns

5
from organvm-iv-taxis/a-i--skills

Implement real-time features with WebSockets, Server-Sent Events, and long polling. Covers connection management, room-based messaging, presence tracking, and scaling strategies. Triggers on WebSocket implementation, real-time communication, or live update feature requests.

react-three-fiber-patterns

5
from organvm-iv-taxis/a-i--skills

Build interactive 3D experiences in React using react-three-fiber (R3F), drei helpers, and shader integration. Covers scene composition, performance optimization, and animation patterns. Triggers on R3F development, React + Three.js, or declarative 3D scene requests.

python-packaging-patterns

5
from organvm-iv-taxis/a-i--skills

Structure Python projects for distribution with pyproject.toml, src layouts, dependency management, and publishing workflows. Covers packaging tools (hatch, setuptools, flit, poetry), versioning strategies, and editable installs. Triggers on Python project setup, packaging configuration, or dependency management requests.

prompt-engineering-patterns

5
from organvm-iv-taxis/a-i--skills

Design effective prompts for LLM agents with structured input/output formats, chain-of-thought reasoning, few-shot examples, and system prompt architecture. Covers Claude-specific patterns and multi-turn conversation design. Triggers on prompt design, LLM interaction patterns, or system prompt architecture requests.

postgres-advanced-patterns

5
from organvm-iv-taxis/a-i--skills

Advanced PostgreSQL patterns for performance optimization, complex queries, indexing strategies, and database design