fastapi
Skill1 starsChanged 5 months agoMITView on GitHub
FastAPI best practices and conventions. Use when working with FastAPI APIs, Pydantic models, dependencies, streaming responses including Server-Sent Events (SSE), and serving frontend apps. Keeps FastAPI code clean and up to date with the latest features and patterns.
27 other projects use a version of this, 8 of them edited.
Adopted by
Most recently taken up by
- gurupak/claude-skillstheir own version, first seen Oct 25, 2026
- DongDuong2001/pudo-code-systemtheir own version, first seen Oct 13, 2026
- G1Joshi/Agent-Skillstheir own version, first seen Oct 13, 2026
- nimadorostkar/Claude-Skills-collectiontheir own version, first seen Oct 13, 2026
- qyndex/claude-inittheir own version, first seen Oct 13, 2026
- Alteriom/ai-dev-skillstheir own version, first seen Oct 11, 2026
Used with
Projects with it also use nextjs, docker and 5 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.
OpenAISkillnextjs
Next.js App Router expert guidance. Use when building, debugging, or architecting Next.js applications — routing, Server Components, Server Actions, Cache Components, layouts, middleware/proxy, data fetching, rendering strategies, and deployment on Vercel.
Also in 4 projects that use this
wrsmith108Skilldocker
Container-based development for isolated, reproducible environments. Use when running npm commands, installing packages, executing code, or managing project dependencies. Trigger phrases include "npm install", "run the build", "start the server", "install package", or any code execution request.
Also in 4 projects that use this
VercelSkillreact
React renderer for json-render that turns JSON specs into React components. Use when working with @json-render/react, building React UIs from JSON, creating component catalogs, or rendering AI-generated specs.
Also in 3 projects that use this
rogue-dev-studioSkillpython
Python 3.13 with uv package manager via mise. Use when the project needs this capability or the user / team manifest asks for it. Use for specialized `python` work when listed in TEAM.yaml or explicitly requested.
Also in 3 projects that use this
MicrosoftSkilltypescript
TypeScript best practices for this monorepo. Use this skill when: (1) writing new TypeScript code, (2) reviewing TypeScript code, (3) working with API responses, fetch calls, or JSON parsing, (4) adding or modifying types and interfaces.
Also in 3 projects that use this
BlockSkillplan
Draft a TDD, PRD, or lightweight plan in the conversation without committing it.
Also in 3 projects that use this
Other versions27 projects use a version of this.
Word for word · 1
- arunkumar201/learning-ai★ 1100% same
Edited · 8
- Bbar0n234/learnflow-ai★ 3554% same
- aptitude-stack/registery★ 154% same
- jpoindexter/theft-kit★ 154% same
- solenspace/solenautum★ 154% same
- eggboy/skills★ 035% same
- gabepublic/api-autonom-test-01★ 054% same
- peakdong68/my-skills★ 054% same
- ui-iids/claude-skills★ 033% same
Wrote their own version · 18
- kid-sid/claude-spellbook★ 190same name
- youlaitech/youlai-skills★ 63same name
- nimadorostkar/Claude-Skills-collection★ 33same name
- G1Joshi/Agent-Skills★ 15same name
- harness-studio/harness-studio★ 9same name
- DongDuong2001/pudo-code-system★ 5same name
- jawwad-ali/claude-code-skills★ 4same name
- Spardutti/claude-skills★ 3same name
- ffsshhttiikk/opencode-agents-skills★ 2same name
- qyndex/claude-init★ 2same name
8 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 repository5 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- db-migrateSkill
- db-resetSkill
- new-migrationSkill
- supabase-postgres-best-practicesSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
21 rules. 0 are common, 7 are distinctive, and 14 are very specific to this project.
0
Common
Most of the 24 edited versions we read keep these.
7
Distinctive
This author's own choices. Worth a look.
14
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 23
Run the development server on localhost with reload:
- Distinctive: line 29
Run the production server:
- Very specific: line 35
Prefer declaring the entrypoint in pyproject.toml:
- Distinctive: line 42
When adding the entrypoint is not possible, or the user explicitly asks not to, pass the app file path:
- Very specific: line 50
Always prefer the Annotated style for parameter and dependency declarations.
- Very specific: line 52
Use Annotated for parameter declarations, including Path, Query, Header, etc.:
- Very specific: line 70
Use Annotated for dependencies with Depends().
- Very specific: line 94
Do not use ... as a default value for required parameters or model fields.
- Distinctive: line 120
When possible, include a return type.
- Very specific: line 141
Use response_model when the type you return is not the same as the public schema you want to validate, filter, document, and serialize.
- Very specific: line 145
Do not use ORJSONResponse or UJSONResponse, they are deprecated.
- Distinctive: line 147
Instead, declare a return type or response model.
- Very specific: line 151
When declaring routers, prefer to add router-level parameters like prefix, tags, and shared dependencies to the router itself instead of in …
- Very specific: line 182
Use app.frontend() to serve a built static frontend app, for example a directory generated by Vite, Astro, Angular, Svelte, Vue, or a …
- Very specific: line 192
Use router.frontend() when the frontend belongs to an APIRouter.
- Very specific: line 208
Use dependencies when the logic can't be declared in Pydantic validation, depends on external resources, needs cleanup with yield, or is …
- Very specific: line 216
Use async *path operations* only when fully certain that the logic called inside is compatible with async and await, and that it doesn't …
- Very specific: line 238
Make sure blocking code is not run inside of async functions.
- Distinctive: line 240
When needing to mix blocking and async code, see Asyncer in the other tools reference.
- Very specific: line 278
Do not use Pydantic RootModel.
- Distinctive: line 298
Don't mix HTTP operations in a single function.
“Common” is measured: kept by at least 6 in 10 of the 24 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
Official FastAPI skill to write code with best practices, keeping up to date with new versions and features.
Quick Reference
- Serve frontend apps: use
app.frontend()orrouter.frontend()for built frontend assets; see Serve Frontend Apps. - Server-Sent Events (SSE): use
response_class=EventSourceResponseandyield; see Streaming and the streaming reference. - JSON Lines and byte streaming: see the streaming reference.
- Dependencies: use
Annotated[..., Depends(...)]; see Dependency Injection and the dependency injection reference foryield, scopes, and class dependencies. - Response models: prefer return types; use
response_modelwhen the public response schema differs from the internal return value; see the response reference. - Pydantic models: do not use ellipsis or
RootModel; see the Pydantic reference. - Routing: declare router-level prefix, tags, and shared dependencies on the
APIRouter; see the path operation reference. - Tooling and related libraries: use uv, Ruff, ty, Asyncer, SQLModel, and HTTPX when applicable; see the other tools reference.
Use the fastapi CLI
Run the development server on localhost with reload:
fastapi devRun the production server:
fastapi runPrefer declaring the entrypoint in pyproject.toml:
[tool.fastapi]
entrypoint = "my_app.main:app"When adding the entrypoint is not possible, or the user explicitly asks not to, pass the app file path:
fastapi dev my_app/main.pyUse Annotated
Always prefer the Annotated style for parameter and dependency declarations. It keeps function signatures working in other contexts, respects the types, and allows reusability.
Use Annotated for parameter declarations, including Path, Query, Header, etc.:
from typing import Annotated
from fastapi import FastAPI, Path, Query
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(
item_id: Annotated[int, Path(ge=1, description="The item ID")],
q: Annotated[str | None, Query(max_length=50)] = None,
):
return {"message": "Hello World"}Use Annotated for dependencies with Depends(). Unless asked not to, create a new type alias for the dependency to allow reusing it:
from typing import Annotated
from fastapi import Depends, FastAPI
app = FastAPI()
def get_current_user():
return {"username": "johndoe"}
CurrentUserDep = Annotated[dict, Depends(get_current_user)]
@app.get("/items/")
async def read_item(current_user: CurrentUserDep):
return {"message": "Hello World"}Do not use Ellipsis for path operations or Pydantic models
Do not use ... as a default value for required parameters or model fields. It's not needed and not recommended.
from typing import Annotated
from fastapi import FastAPI, Query
from pydantic import BaseModel, Field
app = FastAPI()
class Item(BaseModel):
name: str
description: str | None = None
price: float = Field(gt=0)
@app.post("/items/")
async def create_item(item: Item, project_id: Annotated[int, Query()]):
return itemSee the Pydantic reference for more details.
Return Type or Response Model
When possible, include a return type. It will be used to validate, filter, document, and serialize the response.
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: str | None = None
@app.get("/items/me")
async def get_item() -> Item:
return Item(name="Plumbus", description="All-purpose home device")Return types or response models filter data to avoid exposing sensitive information, and they let Pydantic serialize the data on the Rust side for performance.
Use response_model when the type you return is not the same as the public schema you want to validate, filter, document, and serialize. See the response reference.
Performance
Do not use ORJSONResponse or UJSONResponse, they are deprecated.
Instead, declare a return type or response model. Pydantic will handle the data serialization on the Rust side.
Including Routers
When declaring routers, prefer to add router-level parameters like prefix, tags, and shared dependencies to the router itself instead of in include_router().
from fastapi import APIRouter, Depends, FastAPI
app = FastAPI()
def get_current_user():
return {"username": "johndoe"}
router = APIRouter(
prefix="/items",
tags=["items"],
dependencies=[Depends(get_current_user)],
)
@router.get("/")
async def list_items():
return []
app.include_router(router)See the path operation reference for more routing patterns.
Serve Frontend Apps
Use app.frontend() to serve a built static frontend app, for example a directory generated by Vite, Astro, Angular, Svelte, Vue, or a similar tool.
from fastapi import FastAPI
app = FastAPI()
app.frontend("/", directory="dist")Use router.frontend() when the frontend belongs to an APIRouter; normal router prefix behavior applies when the router is included.
from fastapi import APIRouter, FastAPI
app = FastAPI()
router = APIRouter(prefix="/admin")
router.frontend("/", directory="admin-dist")
app.include_router(router)app.frontend() and router.frontend() are low-priority routes: regular API routes are matched first, then frontend files and client-side routing fallbacks. Use this for single-page apps and built frontend assets instead of mounting StaticFiles manually.
Dependency Injection
Use dependencies when the logic can't be declared in Pydantic validation, depends on external resources, needs cleanup with yield, or is shared across endpoints.
Apply shared dependencies at the router level via dependencies=[Depends(...)].
See the dependency injection reference for detailed patterns including yield with scope, and class dependencies.
Async vs Sync path operations
Use async path operations only when fully certain that the logic called inside is compatible with async and await, and that it doesn't block.
from fastapi import FastAPI
app = FastAPI()
@app.get("/async-items/")
async def read_async_items():
data = await some_async_library.fetch_items()
return data
@app.get("/items/")
def read_items():
data = some_blocking_library.fetch_items()
return dataIn case of doubt, or by default, use regular def functions. They will be run in a threadpool so they don't block the event loop. The same rules apply to dependencies.
Make sure blocking code is not run inside of async functions. The logic will work, but will damage performance heavily.
When needing to mix blocking and async code, see Asyncer in the other tools reference.
Streaming (JSON Lines, SSE, bytes)
To stream Server-Sent Events, use response_class=EventSourceResponse and yield items from the endpoint.
from collections.abc import AsyncIterable
from fastapi import FastAPI
from fastapi.sse import EventSourceResponse, ServerSentEvent
app = FastAPI()
@app.get("/events", response_class=EventSourceResponse)
async def stream_events() -> AsyncIterable[ServerSentEvent]:
yield ServerSentEvent(data={"status": "started"}, event="status", id="1")Plain objects are automatically JSON-serialized as data: fields. Use ServerSentEvent for full control over SSE fields (event, id, retry, comment) and raw_data for pre-formatted strings.
See the streaming reference for JSON Lines, Server-Sent Events (EventSourceResponse, ServerSentEvent), and byte streaming (StreamingResponse) patterns.
Tooling
See the other tools reference for details on uv, Ruff, ty for package management, linting, type checking, formatting, etc.
Other Libraries
See the other tools reference for details on other libraries:
- Asyncer for handling async and await, concurrency, mixing async and blocking code, prefer it over AnyIO or asyncio.
- SQLModel for working with SQL databases, prefer it over SQLAlchemy.
- HTTPX for interacting with HTTP (other APIs), prefer it over Requests.
Do not use Pydantic RootModels
Do not use Pydantic RootModel; instead use regular type annotations with Annotated and Pydantic validation utilities.
from typing import Annotated
from fastapi import Body, FastAPI
from pydantic import Field
app = FastAPI()
@app.post("/items/")
async def create_items(items: Annotated[list[int], Field(min_length=1), Body()]):
return itemsFastAPI supports these type annotations and will create a Pydantic TypeAdapter for them, so types work normally without custom wrapper models. See the Pydantic reference.
Use one HTTP operation per function
Don't mix HTTP operations in a single function. Having one function per HTTP operation helps separate concerns and organize the code.
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
@app.get("/items/")
async def list_items():
return []
@app.post("/items/")
async def create_item(item: Item):
return itemSee the path operation reference for more examples.
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.

