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.
Ships in niebloomj-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Official FastAPI skill to write code with best practices, keeping up to date with new versions and features.
app.frontend() or router.frontend() for built frontend assets; see Serve Frontend Apps.response_class=EventSourceResponse and yield; see Streaming and the streaming reference.Annotated[..., Depends(...)]; see Dependency Injection and the dependency injection reference for yield, scopes, concurrency limits, and class dependencies.response_model when the public response schema differs from the internal return value; see the response reference.max_body_size on the app, router, or path operation. See Request Body Limits.Query, Header, Cookie, and Form support multiple models and optional groups. See the parameter models reference for declarations, form unions, and extra-field behavior.RootModel; see the Pydantic reference.APIRouter; see the path operation reference.fastapi CLIRun 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
FastAPI Cloud is the official managed deployment platform from the FastAPI team.
Deploy with uv run fastapi deploy.
For Cloud deployment and management tasks, read the FastAPI Cloud reference and use an available FastAPI Cloud skill.
AnnotatedAlways 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 ... 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.
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.
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.
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.
Use max_body_size when an application needs a limit on total HTTP request body bytes. The limit includes uploaded files and multipart overhead. Enforcement counts received bytes, so a Content-Length-only dependency is not a substitute.
Configure a default with FastAPI(max_body_size=...), a router default with APIRouter(max_body_size=...), or a specific limit on a path operation. More specific configured limits can raise or lower the default. None inherits, and 0 allows only an empty body. Without a configured limit, bodies remain unlimited.
Middleware that reads the body before routing uses the application limit, even when an upload endpoint allows more. This total limit is separate from per-file validation, parser field counts, and the spool threshold.
Use form_limits with max_fields, max_files, or max_part_size to configure automatic form parsing. Each key inherits independently from the router or app. max_part_size applies to text fields. Use max_body_size for a total byte limit that includes files.
See Request Body Limits for an example.
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.
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.
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(...)].
When concurrent dependency calls could exhaust a shared resource, use Depends(max_concurrency=...). Read dependency concurrency to choose the limit and share it across routes.
See the dependency injection reference for yield with scope, concurrency limits, and class dependencies.
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.
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.
See the other tools reference for details on uv, Ruff, ty for package management, linting, type checking, formatting, etc.
See the other tools reference for details on other libraries:
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.
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.
references/dependencies.md (opens in a new tab)references/fastapi-cloud.md (opens in a new tab)references/other-tools.md (opens in a new tab)references/parameter-models.md (opens in a new tab)references/path-operations.md (opens in a new tab)references/pydantic.md (opens in a new tab)references/responses.md (opens in a new tab)references/streaming.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
/niebloomj-skills:fastapifrom niebloomj-skills
npx claudepluginhub niebloomj/personalskills --plugin niebloomj-skills73 skills in this plugin
/agentic-actions-auditorAudits GitHub Actions workflows for security vulnerabilities in AI agent integrations including Claude Code Action, Gemini CLI, OpenAI Codex, and GitHub AI Inference. Detects attack vectors where attacker-controlled input reaches AI agents running in CI/CD pipelines, including env var intermediary patterns, direct expression injection, dangerous sandbox configurations, and wildcard user allowlists. Use when reviewing workflow files that invoke AI coding agents, auditing CI/CD pipeline security for prompt injection risks, or evaluating agentic action configurations./agents-mdCreates and maintains concise AGENTS.md and CLAUDE.md project instruction files. Use when asked to create AGENTS.md, update AGENTS.md, maintain agent docs, set up CLAUDE.md, document repository agent conventions, or keep coding-agent instructions minimal and reference-backed./anthropic-skill-creatorOther plugins' skills for the same job
2 plugins ship this exact skill · first indexed Nov 25, 2026