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 [blocked]. - JSON Lines and byte streaming: see the streaming reference [blocked].
- OpenTelemetry: use FastAPI's native traces, metrics, and logs. See OpenTelemetry.
- Dependencies: use
Annotated[..., Depends(...)]; see Dependency Injection and the dependency injection reference [blocked] 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 [blocked]. - Pydantic models: do not use ellipsis or
RootModel; see the Pydantic reference [blocked]. - Routing: declare router-level prefix, tags, and shared dependencies on the
APIRouter; see the path operation reference [blocked]. - Tooling and related libraries: use uv, Ruff, ty, Asyncer, SQLModel, and HTTPX when applicable; see the other tools reference [blocked].
Use the fastapi CLI
Run the development server on localhost with reload:
Run the production server:
Prefer declaring the entrypoint in pyproject.toml:
When adding the entrypoint is not possible, or the user explicitly asks not to, pass the app file path:
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.:
Use Annotated for dependencies with Depends(). Unless asked not to, create a new type alias for the dependency to allow reusing it:
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.
See the Pydantic reference [blocked] 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.
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 [blocked].
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().
See the path operation reference [blocked] 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.
Use router.frontend() when the frontend belongs to an APIRouter; normal router prefix behavior applies when the router is included.
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 [blocked] 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.
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 [blocked].
Streaming (JSON Lines, SSE, bytes)
To stream Server-Sent Events, use response_class=EventSourceResponse and yield items from the endpoint.
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 [blocked] for JSON Lines, Server-Sent Events (EventSourceResponse, ServerSentEvent), and byte streaming (StreamingResponse) patterns.
Tooling
See the other tools reference [blocked] for details on uv, Ruff, ty for package management, linting, type checking, formatting, etc.
Other Libraries
See the other tools reference [blocked] 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.
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 [blocked].
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.
See the path operation reference [blocked] for more examples.


