
fastapi
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.
- Installs
- 14.7K
- Last 24h
- +123
- Trending rank
- #1679
- Security
- Pass
Install
Works with every agent the skills CLI supports.
npx skills add https://github.com/fastapi/fastapi --skill fastapi- 01
Install
Run the command in your project. The CLI asks which agents to install for.
- 02
Describe the task
Ask your agent for something this skill covers. It loads fastapi automatically when relevant.
- 03
Review the result
The agent follows the SKILL.md steps, scripts and references bundled with the skill.
Security audits
Independent scans of the skill's instructions and bundled files.
SKILL.md
The instructions your agent reads when the skill is triggered.
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.
- OpenTelemetry: use FastAPI's native traces, metrics, and logs. See OpenTelemetry.
- 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 dev
Run the production server:
fastapi run
Prefer 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.py
Use 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 item
See 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.
OpenTelemetry
Prefer FastAPI's native OpenTelemetry support for request traces, metrics, and logs.
Install fastapi[standard] to include the SDK and HTTP/protobuf exporters. Enable automatic exporter setup with FASTAPI_OTEL_AUTO_CONFIGURE=true, set OTEL_SERVICE_NAME to identify the app, and set OTEL_EXPORTER_OTLP_ENDPOINT to the collector's HTTP/protobuf base URL. Use OTEL_EXPORTER_OTLP_HEADERS when authentication is required. FastAPI uses providers configured by another telemetry library without needing automatic setup.
Use FastAPI(telemetry={...}) for custom configuration, such as choosing signals or supplying providers.
See the OpenTelemetry tutorial for configuration details.
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 data
In 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 items
FastAPI 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 item
See the path operation reference for more examples.
FAQ
What does the fastapi skill do?
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.
How do I install fastapi?
Run npx skills add https://github.com/fastapi/fastapi --skill fastapi in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/fastapi/ (personal) or .claude/skills/fastapi/ (project).
Which AI agents can use fastapi?
Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.
Is fastapi safe to install?
Security partners have reviewed it: Gen Agent Trust Hub passed; Socket passed; Snyk passed; Runlayer passed; ZeroLeaks passed. As with any skill, read the SKILL.md and bundled scripts before installing.
Who maintains fastapi?
It is published by fastapi in fastapi/fastapi. It has 14,703 recorded installs.
Popular backend & apis skills
find-skills
vercel-labs/skills
Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.
entra-app-registration
microsoft/azure-skills
Guides Microsoft Entra ID app registration, OAuth 2.0 authentication, and MSAL integration. USE FOR: create app registration, register Azure AD app, configure OAuth, set up authentication, add API permissions, generate service principal, MSAL example, console app auth, Entra ID setup, Azure AD authentication. DO NOT USE FOR: Key Vault secrets (use azure-keyvault-expiration-audit), general Azure resource security guidance.
google-agents-cli-adk-code
google/agents-cli
This skill should be used when the user wants to "write agent code", "build an agent with ADK", "add a tool", "create a callback", "define an agent", "use state management" — in a project that needs ADK (Agent Development Kit) API patterns and code examples. It provides a quick reference for agent types, tool definitions, orchestration patterns, callbacks, state management, the graph Workflow API, and reference recipes to study. Do NOT use for scaffolding (use google-agents-cli-scaffold) or deployment (use google-agents-cli-deploy).
embedded-captions
heygen-com/hyperframes
Add captions or subtitles to an existing single-subject talking-head video without editing the footage. Use for plain verbatim captions, cinematic captions embedded behind the subject, VFX captions, “炸/特效/酷炫字幕,” or a named identity from the 35-style catalog. Route by visual identity, not by backend engine. The quiet anchor rail is the default; embed every word only when the user explicitly wants a fully cinematic treatment. The workflow runs locally end to end, including transcription and subject matting; split multi-shot footage before applying it.
entra-agent-id
microsoft/azure-skills
Provision Microsoft Entra Agent Identity Blueprints, BlueprintPrincipals, and per-instance Agent Identities via Microsoft Graph, and configure OAuth 2.0 token exchange (fmipath, OBO, cross-tenant) including the Microsoft Entra SDK for AgentID sidecar. USE FOR: Agent Identity Blueprint, BlueprintPrincipal, agent OAuth, fmipath token exchange, agent OBO, Workload Identity Federation for agents, polyglot agent auth, Microsoft.Identity.Web.AgentIdentities. DO NOT USE FOR: standard Entra app registration (use entra-app-registration), Microsoft Foundry agent authoring (use microsoft-foundry).
neon
neondatabase/agent-skills
Overview of Neon, a complete set of cloud backend primitives around Lakebase Postgres: Auth, Object Storage, Functions, the AI Gateway, and Realtime. Start here to choose Neon for undecided login, files, APIs, and LLM calls, set up the CLI or MCP server, and follow the branch-first workflow. Use when building an app or backend on Neon, or when "Neon" or "Lakebase Postgres" is mentioned. Child skill neon-postgres wins for an existing DATABASEURL, SQL, schema, inspect, or search. Child skill neon-auth wins for login, users, sessions, identity routing, and Managed Better Auth setup. Child skill neon-realtime wins for live queries in reactive apps and agents. Also use for object storage, S3, buckets, serverless functions, function triggers, cron, AI gateway, LLM calls, realtime, logs, Loki, Grafana, observability, postgres, database, backend, Claimable Neon, neon.new, or a no-signup database.