fastapi-patterns
Skill4 starsChanged 7 months agoMITArchived repositoryView on GitHub
Load when working with: FastAPI routers, Pydantic models, dependency injection, middleware, ASGI lifecycle, HTTP endpoints, background tasks. All FastAPI projects follow Hexagonal Architecture: The core/ layer MUST NOT import from fastapi, sqlalchemy, or any adapter library. The api/ layer MUST NOT contain business logic — only validation and routing. Register in create_app(): When HTMX is needed, see htmx-frontend skill. Key principle: HTMX routes live in a separate router (api/routers/pages.py) and return HTMLResponse / Jinja2 TemplateResponse. JSON API routes stay clean…
12 other projects use a version of this.
Adopted by
Most recently taken up by
- ku5ic/claude-kittheir own version, first seen Oct 6, 2026
- imMamdouhaboammar/tiktok-growth-automation-meshtheir own version, first seen Oct 1, 2026
- productionx-in/Core-Skillstheir own version, first seen Sep 29, 2026
- templetongroup/radianttheir own version, first seen Sep 17, 2026
- bjornjee/skillstheir own version, first seen Sep 8, 2026
- SamuelNDCE/claude-super-skill-librarytheir own version, first seen Aug 1, 2026
Used with
Projects with it also use typescript-patterns, docker-patterns and 4 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.
cohen-lielSkilltypescript-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
LangChainSkilldocker-patterns
Best practices for Docker containerization and multi-stage builds
Also in 4 projects that use this
FaisalAlqarniSkillgolang-patterns
Idiomatic Go patterns, best practices, and conventions for building robust, efficient, and maintainable Go applications.
Also in 3 projects that use this
benshapyroSkillreact-patterns
Modern React patterns for TypeScript applications including hooks, state management, and component composition. Use when building React components, managing state, or implementing React best practices.
Also in 3 projects that use this
xfstudioSkillpython-patterns
Python development principles and decision-making. Framework selection, async patterns, type hints, project structure. Teaches thinking, not copying.
Also in 3 projects that use this
WorldFlowAISkillverification-loop
Also in 3 projects that use this
Other versions12 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 12
- templetongroup/radiant★ 113same name
- 4444J99/a-i--skills★ 17same name
- hieutrtr/ai1-skills★ 8same name
- peopleforrester/claude-dotfiles★ 3same name
- aragaobruno/monster-antigravity★ 2same name
- bjornjee/skills★ 2same name
- JunMystery/Agent-Guidance-Python★ 2same name
- ku5ic/claude-kit★ 2same name
- productionx-in/Core-Skills★ 1same name
- SamuelNDCE/claude-super-skill-library★ 1same name
2 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository23 other files it gives its agents.
- .claude/CLAUDE.mdCLAUDE.md
- llms.txtllms.txt
- claude-api-patternsSkill
- critical-analysisSkill
- database-migration-safetySkill
- data-validationSkill
- design-doc-creatorSkill
- experiment-trackingSkill
- github-actionsSkill
- htmx-frontendSkill
- infra-yandex-cloudSkill
- langgraph-patternsSkill
- ml-data-handlingSkill
- multimodal-routerSkill
- nlp-slm-patternsSkill
- predictive-analyticsSkill
- prompt-engineeringSkill
- python-project-standardsSkill
- rag-vector-dbSkill
- skill-developerSkill
- supply-chain-auditorSkill
- test-first-patternsSkill
- windows-developerSkill
The file
We split this skill into the rules it gives an agent
2 rules. 0 are common, 1 is distinctive, and 1 is very specific to this project.
0
Common
Most of the 9 edited versions we read keep these.
1
Distinctive
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 9
All FastAPI projects follow Hexagonal Architecture:
- Very specific: line 137
When HTMX is needed, see htmx-frontend skill.
“Common” is measured: kept by at least 6 in 10 of the 9 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
FastAPI Patterns
When to Load This Skill
Load when working with: FastAPI routers, Pydantic models, dependency injection, middleware, ASGI lifecycle, HTTP endpoints, background tasks.
Architectural Contract
All FastAPI projects follow Hexagonal Architecture:
api/ → adapters IN (HTTP boundary)
core/ → domain (pure Python, zero framework imports)
services/ → application (orchestrates core + adapters)
adapters/ → adapters OUT (DB, LLM, S3, external APIs)
models/ → schemas (Pydantic — request, response, internal)The core/ layer MUST NOT import from fastapi, sqlalchemy, or any adapter library.
The api/ layer MUST NOT contain business logic — only validation and routing.
Application Entry Point
from contextlib import asynccontextmanager
from fastapi import FastAPI
from src.project_name.api.routers import health, items
from src.project_name.core.config import settings
@asynccontextmanager
async def lifespan(app: FastAPI):
yield
def create_app() -> FastAPI:
app = FastAPI(
title=settings.app_name,
version=settings.app_version,
lifespan=lifespan,
)
app.include_router(health.router, prefix="/health", tags=["health"])
app.include_router(items.router, prefix="/api/v1/items", tags=["items"])
return app
app = create_app()Router Pattern
from fastapi import APIRouter, Depends, HTTPException, status
from src.project_name.models.item import ItemCreate, ItemResponse
from src.project_name.services.item_service import ItemService
router = APIRouter()
def get_item_service() -> ItemService:
return ItemService()
@router.post("/", response_model=ItemResponse, status_code=status.HTTP_201_CREATED)
async def create_item(
payload: ItemCreate,
service: ItemService = Depends(get_item_service),
) -> ItemResponse:
return await service.create(payload)Service Layer Pattern
from src.project_name.adapters.item_repository import ItemRepository
from src.project_name.core.domain import Item
from src.project_name.models.item import ItemCreate, ItemResponse
class ItemService:
def __init__(self, repository: ItemRepository | None = None) -> None:
self._repo = repository or ItemRepository()
async def create(self, payload: ItemCreate) -> ItemResponse:
domain_item = Item.from_create(payload)
saved = await self._repo.save(domain_item)
return ItemResponse.model_validate(saved)Pydantic Models Convention
from pydantic import BaseModel, Field
class ItemCreate(BaseModel):
name: str = Field(..., min_length=1, max_length=200)
description: str | None = None
class ItemResponse(BaseModel):
model_config = {"from_attributes": True}
id: int
name: str
description: str | NoneError Handling
from fastapi import Request
from fastapi.responses import JSONResponse
from src.project_name.core.exceptions import DomainError, NotFoundError
async def domain_error_handler(request: Request, exc: DomainError) -> JSONResponse:
return JSONResponse(status_code=400, content={"detail": str(exc)})
async def not_found_handler(request: Request, exc: NotFoundError) -> JSONResponse:
return JSONResponse(status_code=404, content={"detail": str(exc)})Register in create_app():
app.add_exception_handler(DomainError, domain_error_handler)
app.add_exception_handler(NotFoundError, not_found_handler)HTMX Integration
When HTMX is needed, see htmx-frontend skill. Key principle: HTMX routes live in a separate router (api/routers/pages.py) and return HTMLResponse / Jinja2 TemplateResponse. JSON API routes stay clean and separate.
Health Check (Standard)
from fastapi import APIRouter
from fastapi.responses import JSONResponse
router = APIRouter()
@router.get("/")
async def health() -> JSONResponse:
return JSONResponse({"status": "ok"})Running with uvicorn
uv run uvicorn src.project_name.main:app --reload --host 0.0.0.0 --port 8000Further Resources
resources/dependency-injection.md— advanced DI patternsresources/background-tasks.md— async background jobsresources/middleware.md— CORS, logging, request ID middleware
Streaming & Async Patterns
Server-Sent Events (SSE) for LLM Streaming
from fastapi import APIRouter
from fastapi.responses import StreamingResponse
import asyncio
router = APIRouter()
async def token_generator(prompt: str):
async for token in llm_service.stream(prompt):
yield f"data: {token}\n\n"
yield "data: [DONE]\n\n"
@router.post("/stream")
async def stream_response(request: PromptRequest) -> StreamingResponse:
return StreamingResponse(
token_generator(request.prompt),
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
)WebSocket Pattern
from fastapi import WebSocket, WebSocketDisconnect
@router.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket) -> None:
await websocket.accept()
try:
while True:
data = await websocket.receive_text()
async for token in llm_service.stream(data):
await websocket.send_text(token)
except WebSocketDisconnect:
passAsync Background Tasks
from fastapi import BackgroundTasks
async def process_batch(job_id: str, records: list[dict]) -> None:
result = await ml_service.run(records)
await job_store.save(job_id, result)
@router.post("/jobs")
async def create_job(
payload: BatchRequest,
background_tasks: BackgroundTasks,
) -> dict:
job_id = str(uuid4())
background_tasks.add_task(process_batch, job_id, payload.records)
return {"job_id": job_id, "status": "queued"}Streaming Response from Anthropic Claude
from anthropic import AsyncAnthropic
client = AsyncAnthropic()
async def claude_token_generator(prompt: str):
async with client.messages.stream(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[{"role": "user", "content": prompt}],
) as stream:
async for text in stream.text_stream:
yield f"data: {text}\n\n"
yield "data: [DONE]\n\n"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
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.

