Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Fastapi Knowledge Patch?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/nevaberry-fastapi-knowledge-patch-nevaberry-plugins)
---
name: fastapi-knowledge-patch
description: FastAPI
version: "0.165.0"
license: MIT
metadata:
author: Nevaberry
---
# FastAPI knowledge patch
Load this skill when changing FastAPI request validation, dependency lifetimes,
responses, streaming, frontend mounts, deployment, or OpenAPI generation.
The references also cover Pydantic, SQLModel, Starlette, and Uvicorn compatibility.
Use the topic reference for examples and the precise release conditions.
## Reference index
| Reference | Topics |
| --- | --- |
| [Upgrading and compatibility](references/upgrading-and-compatibility.md) | Python requirements, dependency pins, Pydantic migration, proxy prefixes, OpenTelemetry |
| [Requests and security](references/requests-and-security.md) | Defaults, forms, uploads, aliases, parameter models, content types, authentication |
| [Dependency injection](references/dependency-injection.md) | Yield scopes, cleanup, concurrency, caching, callables, lifespan |
| [Responses and streaming](references/responses-and-streaming.md) | Serialization, response models, JSON Lines, SSE, raw streams, bodyless responses |
| [OpenAPI and Pydantic](references/openapi-and-pydantic.md) | Schema generation, validators, dynamic models, metadata, typing, dataclasses |
| [Frontend, CLI, and documentation](references/frontend-cli-and-docs.md) | Frontend fallback and dependencies, routers, CLI entrypoints, API docs, templates |
| [SQLModel](references/sqlmodel.md) | Dependency requirements, fields, aliases, columns, indexes, typed write statements |
| [Starlette](references/starlette.md) | Application registration, lifespan state, middleware, CORS, files, multipart limits, tests |
| [Uvicorn](references/uvicorn.md) | Workers, reloads, custom protocols, shutdown, ASGI scopes, proxies, WebSockets |
## Breaking changes and deprecations
### Runtime and Pydantic migration
FastAPI 0.162.6 raises the Python minimum to 3.11; use `fastapi<0.162.6`
on Python 3.10. FastAPI 0.162.4 requires AnyIO 4.1.0 or later at runtime.
FastAPI 0.128.0 requires V2 models even when `pydantic.v1` is importable.
FastAPI 0.135.2 requires `pydantic>=2.9.0`; update a lower pin before upgrading.
Pydantic 2.12 raises a startup error if `pydantic-core` differs from its exact
required version. Update both pins together when managing them separately.
### Constructor, proxy, and parameter keywords
FastAPI 0.145.0 removes `openapi_prefix` and the `**extra` catch-all from
`FastAPI()`. From 0.146.0, the application's `root_path` argument is deprecated;
configure the ASGI root path on the server with `fastapi run --root-path /api/v1`.
FastAPI 0.155.0 removes `**extra` from `Path`, `Query`, `Header`, `Cookie`,
`Body`, `Form`, and `File`; unknown keywords raise `TypeError`.
Use `Query(json_schema_extra={"custom": "value"})` for custom schema properties.
### JSON request media types
From FastAPI 0.132.0, JSON request bodies require a valid JSON `Content-Type`,
such as `application/json`, by default. `FastAPI(strict_content_type=False)`
keeps accepting JSON from clients that omit the header.
Keep strict checking enabled when network location is the only access control
for a localhost or internal-network JSON API: it protects against cross-site
browser requests that omit content type and credentials and can skip CORS preflight.
### Omission, defaults, and explicit null
From 0.148.0, omitted `Query`, `Header`, `Cookie`, and `Form` parameters and
model fields use defaults without validation unless `validate_default=True`;
default factories run once. Defaulted model fields stay out of
`model_dump(exclude_unset=True)`, and injected defaults stay out of error `input`.
Use `Field(validate_default=True)` for model fields; `Body(validate_default=True)`
is also honored from 0.148.0.
From 0.151.0, explicit JSON `null` is validated as `None` for individual `Body`
parameters. Only nullable types accept it; defaults and factories apply on omission.
An entire `null` body fails when `Body(embed=True)` or multiple body parameters
require an object.
Starting in 0.162.0, omitted booleans in individual form parameters, form models,
and form unions use declared defaults or raise missing-field errors.
Omitted model fields stay out of `model_dump(exclude_unset=True)` and the submitted
fields used for union selection. Normal factories and `validate_default` rules apply.
For an unchecked checkbox to produce `False`, declare
`subscribed: Annotated[bool, Form()] = False`.
### Authentication errors and JSON response classes
From 0.122.0, built-in security classes that returned `403` for missing credentials
return `401`. The default authentication failure includes `WWW-Authenticate`.
For legacy behavior, a security subclass's `make_not_authenticated_error()` can
return an `HTTPException`; see the authentication example in Requests and security.
FastAPI 0.131.0 deprecates `ORJSONResponse` and `UJSONResponse`. Remove the custom
response class and declare a return type or `response_model` to use the default
response's Pydantic JSON serialization added in 0.130.0.
### Pydantic validator and serialization changes
Classmethod after-model validators can raise during model construction in Pydantic
2.12.0 through 2.12.2; the deprecation warning starts in 2.12.3.
Define the validator as an instance method and return `self`.
`FieldInfo.merge_field_infos()` is deprecated as of 2.12.
`model_dump(serialize_as_any=True)` uses runtime-type serialization for every value
and can fail where it previously succeeded. Use `SerializeAsAny[T]` only on fields
that need duck typing to retain annotation-based serialization elsewhere.
### Companion-library migration
Use `fastapi` in place of deprecated `fastapi-slim`, and replace `sqlmodel-slim`
with `sqlmodel`. SQLModel 0.0.31 requires Pydantic V2; use `sqlmodel<0.0.31`
if the app still depends on V1.
In Starlette 1.0, move removed startup/shutdown registration to `lifespan=` and
replace old routing decorators with `Route` and `WebSocketRoute` in `routes=`.
Uvicorn 0.36.1 raises on removed `Config.setup_event_loop()` calls; drop that call
and use `await server.serve()` when running inside an existing event loop.
## Dependency lifetimes and concurrency
FastAPI 0.121.0 adds `Depends(..., scope="function")` for teardown after the path
operation returns and before the response is sent. Parameterless top-level
dependencies support it from 0.121.1. Use `scope="request"` for teardown after sending.
A request-scoped yield dependency can use a yield sub-dependency only when that
sub-dependency is request-scoped. A function-scoped one can use either scope.
FastAPI 0.118.0 runs yield teardown after sending the response and keeps uploads
open until then, allowing a `StreamingResponse` iterator to use yielded resources
or read an `UploadFile`. The reference preserves the earlier cleanup behavior.
Since 0.110.0, caught exceptions are not automatically forwarded from yield
dependencies; use bare `raise` after logging or rollback to propagate the exception.
FastAPI 0.162.5 fixes synchronous dependency cleanup on cancellation; use 0.162.7
or later for the corresponding fix to async yield dependencies.
FastAPI 0.163.0 adds `Depends(max_concurrency=...)` to cap concurrent use of a
dependency. FastAPI 0.123.0 restores request-local cache reuse for dependencies
whose dependency trees use no scopes.
Mounted applications rely on the main application's startup and shutdown hooks;
put setup and cleanup they depend on in the main application's lifespan.
## Request models, aliases, and uploads
Declare multiple models for one location as separate parameters, such as
`page: Annotated[Page, Query()]` and `filters: Annotated[Filters, Query()]`.
Support starts in 0.157.0 for query/header/cookie models, 0.158.0 for form models,
and 0.161.0 for unions of form models. See the reference for nullable model support.
From 0.160.0, each model applies its `extra` configuration to all submitted fields
in its location, including fields declared by sibling models, parameters, or dependencies.
`extra="forbid"` rejects fields outside that model; `"allow"` retains them as extras;
`"ignore"` discards them.
`validation_alias=AliasChoices(...)` accepts alternate input names; fixes differ
by location, so consult the reference for the required release.
From 0.136.3, a default `Header()` binding for `x_trace_id` accepts only `X-Trace-Id`;
use `Header(convert_underscores=False)` for `X_Trace_Id`.
From 0.150.0, an empty filename with empty content counts as a missing upload;
named zero-byte uploads remain valid. File lists skip unselected browser inputs.
FastAPI 0.156.8 preserves an uploaded file's position when converting it to `bytes`.
## Streaming and response serialization
From 0.134.0, a generator path operation can yield one JSON value per line.
JSON Lines uses `application/jsonl`. Annotate with `AsyncIterable[T]` or `Iterable[T]`
to validate, filter, document, and serialize each item; without an annotation,
FastAPI uses `jsonable_encoder()`.
Use `response_class=StreamingResponse` for raw generator chunks. The annotation
then serves type checkers only; set `media_type` on a `StreamingResponse` subclass
and use that class on the route to supply a `Content-Type` header.
For built-in SSE, added in 0.135.0, use `EventSourceResponse` from `fastapi.sse`
as a generator route's `response_class`, including on POST routes.
`ServerSentEvent` sets `event`, `id`, `retry` in milliseconds, or `comment`;
use `data` for JSON or `raw_data` for literal text, with at most one payload field.
Idle streams send a `ping` comment every 15 seconds and set `Cache-Control: no-cache`
and `X-Accel-Buffering: no`. FastAPI 0.136.2 validates outgoing SSE fields.
FastAPI 0.140.13 honors route `status_code` for SSE and JSON Lines; 0.143.3 fixes
serialization of NaN and infinity in both kinds of payload.
When a route explicitly declares `response_class=JSONResponse` and returns ordinary
data, FastAPI applies the response model and passes JSON-compatible content to the
class, which handles encoding it to bytes.
## Frontend mounts, CLI, and documentation
Regular path operations take precedence over frontend files, even across routers.
Only `GET` and `HEAD` can use frontend fallback from 0.138.2.
Default `fallback="auto"` selects `404.html` with status `404` if present, then
`index.html` for browser navigation if only that file exists. That fallback needs
explicit `Accept: text/html` or `application/xhtml+xml`; `Accept: */*` is insufficient.
`fallback=None` disables fallback. `check_dir="auto"`, added in 0.141.0, defers the
directory check during local development with `fastapi dev`.
Frontend requests inherit application/router/include-router dependencies; 0.141.1
runs their registered background tasks and includes their injected response headers.
Set `[tool.fastapi]`'s `entrypoint` in `pyproject.toml` to a `module:object` target.
`fastapi[standard]` includes the Cloud CLI from 0.116.0; use
`fastapi[standard-no-fastapi-cloud-cli]` to omit it from a standard installation.
Routes added after `include_router()` are visible from 0.137.0; use
`iter_route_contexts()` for traversal from 0.137.2 and 0.143.1 or later for included
route metadata. See the reference for ReDoc, external documentation, and templates.
## Schema and model construction
Use `typing_extensions.TypedDict` for Pydantic 2.12 PEP 728 support:
`closed=True` generates `additionalProperties: false`, `extra_items=Any` or `object`
generates `true`, and a concrete extra-item type generates that type's schema.
Pydantic 2.12.3 adds `FieldInfo.asdict()` for exporting annotation, metadata, and
field attributes separately when rebuilding definitions for `create_model()`.
FastAPI 0.129.1 represents `bytes` with `contentMediaType: application/octet-stream`;
update tooling that identifies byte fields by `format: binary`.
FastAPI 0.163.1 fixes OpenAPI for response models containing nested computed fields.
## Instrumentation and parsing limits
Native OpenTelemetry support starts in 0.142.0; applications can start even when
automatic configuration fails from 0.142.2. From 0.143.0, exporter setup from
`OTEL_*` variables requires `FASTAPI_OTEL_AUTO_CONFIGURE=true` or
`FastAPI(telemetry={"auto_configure": True})`. FastAPI Cloud enables automatic setup.
FastAPI 0.164.0 adds a configurable maximum request body size; 0.165.0 adds
configurable form parsing limits.