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)
---
name: fastapi-knowledge-patch
description: FastAPI
version: "0.165.0"
license: MIT
metadata:
author: Nevaberry
---
# FastAPI compatibility guidance
Load this skill when upgrading FastAPI or working on request validation,
dependency cleanup, streaming, frontend serving, OpenAPI, or related Pydantic,
SQLModel, Starlette, and Uvicorn compatibility issues.
Use the topic references for complete behavior, release conditions, and examples.
## Reference index
| Reference | Topics |
| --- | --- |
| [Upgrading and compatibility](references/upgrading-and-compatibility.md) | Runtime requirements, installation extras, dependency pins, proxy prefixes, OpenTelemetry |
| [Dependency injection](references/dependency-injection.md) | Cleanup scopes, cancellation, concurrency, caching, callable inspection, lifespans |
| [Requests and security](references/requests-and-security.md) | Defaults, JSON bodies, forms, files, parameter models, aliases, authentication, routing |
| [OpenAPI and Pydantic](references/openapi-and-pydantic.md) | Model construction, validation, serialization settings, schema generation, annotations |
| [Responses and streaming](references/responses-and-streaming.md) | Response models, JSON Lines, SSE, raw generators, bodyless responses, files |
| [Frontend, CLI, and documentation](references/frontend-cli-and-docs.md) | Frontend fallback, directory checks, dependencies, router traversal, CLI entrypoint, API docs |
| [SQLModel](references/sqlmodel.md) | Runtime and dependency compatibility, field aliases, columns, indexes, typed writes |
| [Starlette](references/starlette.md) | Application registration, templates, typed state, middleware, CORS, multipart, TestClient |
| [Uvicorn](references/uvicorn.md) | Workers, reload, protocol backends, ASGI state, disconnects, proxy settings, logging |
## Breaking changes and deprecations
### Runtime and installation
Use `fastapi<0.162.6` on Python 3.10; FastAPI 0.162.6 requires Python 3.11.
FastAPI 0.162.4 requires AnyIO 4.1.0 or later at runtime.
FastAPI 0.135.2 requires `pydantic>=2.9.0`; update a lower pin before upgrading.
FastAPI 0.128.0 requires V2 models even if `pydantic.v1` remains importable.
Use `fastapi` directly for a base installation: `fastapi-slim` is deprecated
and no longer receives new releases starting with 0.129.2.
Use `fastapi[standard]` to install the CLI and Uvicorn.
To omit the Cloud CLI from a standard installation, use
`pip install "fastapi[standard-no-fastapi-cloud-cli]"`.
### Removed constructor and parameter options
FastAPI 0.145.0 removes `openapi_prefix` and the `**extra` catch-all from
`FastAPI()`. Starting in 0.146.0, the application's `root_path` argument is
deprecated; configure it 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.
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.
For the deprecated WSGI middleware, use `from a2wsgi import WSGIMiddleware`.
### JSON content types and explicit null
Starting in FastAPI 0.132.0, JSON request bodies require a valid JSON
`Content-Type`, such as `application/json`, by default.
`FastAPI(strict_content_type=False)` permits JSON from clients omitting it.
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 the header and credentials and can skip CORS preflight.
From 0.151.0, explicit JSON `null` is validated as `None` for individual `Body`
parameters, whether named or representing the whole body. Only nullable types
accept it; defaults and factories apply on omission. If `Body(embed=True)` or
multiple body parameters require an object, an entire body of `null` fails validation.
### Omitted defaults, empty forms, and browser uploads
From 0.148.0, omitted `Query`, `Header`, `Cookie`, and `Form` parameters and model
fields use defaults without validation unless `validate_default=True` is enabled.
Default factories run once. Defaulted model fields stay out of
`model_dump(exclude_unset=True)`; injected defaults stay out of error `input`.
Use `Field(validate_default=True)` for model fields; `Body(validate_default=True)`
is also honored starting in 0.148.0.
From 0.149.0, an empty scalar string in a form model counts as missing: defaults
or factories apply and the field stays unset, while required fields fail.
Empty strings inside lists are preserved. Form unions gain this behavior in 0.153.0.
From 0.150.0, file parts with both empty filename and empty content count as
missing; file lists skip them. Named zero-byte uploads remain valid.
Form unions gain this browser file handling in 0.153.0.
Starting in 0.162.0, omitted `bool` and `bool | None` form fields use declared
defaults or raise missing-field errors, including in form models and unions.
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 HTML checkbox to produce `False`, declare
`subscribed: Annotated[bool, Form()] = False`.
### Authentication errors and Pydantic warnings
Starting in 0.122.0, built-in security classes that returned `403 Forbidden` for
missing credentials return `401 Unauthorized`. The default authentication failure
includes `WWW-Authenticate`. For legacy `403` behavior, use a security subclass
whose `make_not_authenticated_error()` returns an `HTTPException` instance.
In Pydantic 2.12, define after-model validators as instance methods returning
`self`. Classmethod validators can raise during model construction in 2.12.0
through 2.12.2; the deprecation warning starts in 2.12.3.
`FieldInfo.merge_field_infos()` is deprecated as of Pydantic 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 needing duck typing to retain annotation-based serialization elsewhere.
## Request parameter patterns
Declare multiple models for one location as separate parameters, such as
`page: Annotated[Page, Query()]` and `filters: Annotated[Filters, Query()]`.
This works for query, header, and cookie models from 0.157.0, form models from
0.158.0, and unions of form models from 0.161.0.
For an optional query model, use `filters: Annotated[Filters | None, Query()] = None`
with FastAPI 0.159.0 or later; the reference gives the form and union boundaries.
From 0.160.0, each model applies its `extra` configuration to all submitted fields
in its location, including sibling models, individual parameters, and dependencies.
`extra="forbid"` rejects fields outside that model, `extra="allow"` retains them
as extras, and `extra="ignore"` discards them.
Use Pydantic `validation_alias=AliasChoices(...)` for alternate input names.
The reference gives the fixes for each input location and alias error locations.
For literal header underscores, use `Header(convert_underscores=False)`.
Header model errors use HTTP names from 0.152.0; explicit aliases take precedence,
and `loc_by_alias=False` uses Python field names.
FastAPI 0.164.0 allows a maximum request body size to be configured;
0.165.0 allows form parsing limits to be configured.
## Dependency lifetime and concurrency
Use `Depends(..., scope="function")` for teardown after the path operation returns
and before sending the response, or `scope="request"` for teardown after sending.
Scope selection is available from 0.121.0, including parameterless top-level
dependencies from 0.121.1.
A request-scoped `yield` dependency can use a `yield` sub-dependency only when
that sub-dependency is also request-scoped. A function-scoped dependency can use either.
FastAPI 0.118.0 keeps uploaded files and yielded resources available until after
the response is sent, allowing a `StreamingResponse` iterator to use them.
On 0.106.0 through 0.117.x, pass IDs or independent data to background tasks and
open resources such as database sessions inside the task.
Use bare `raise` after logging or rollback to propagate an exception caught in a
`yield` dependency; automatic forwarding was removed in 0.110.0.
Use 0.162.5 for the synchronous dependency cancellation cleanup fix and 0.162.7
or later for the corresponding async `yield` fix.
From 0.163.0, `Depends(max_concurrency=...)` caps concurrent use of a dependency.
Mounted applications rely on the main application's lifespan for setup and cleanup;
included routers can supply merged lifespan contexts through `APIRouter(lifespan=...)`.
## Streaming responses
From 0.134.0, a path operation can yield one JSON value per line.
JSON Lines uses `application/jsonl`. Annotate generators with `AsyncIterable[T]`
or `Iterable[T]` to validate, filter, document, and serialize each item as `T`;
omit the annotation to use `jsonable_encoder()`.
For raw chunks, use `response_class=StreamingResponse`. A raw generator's return
annotation serves type checkers only; set `media_type` on a `StreamingResponse`
subclass and use it as `response_class` to supply a `Content-Type` header.
For built-in SSE, use `EventSourceResponse` from `fastapi.sse` on a generator route,
including POST routes. Each yielded item becomes JSON in an SSE `data:` field.
```python
from collections.abc import AsyncIterable
from fastapi import FastAPI
from fastapi.sse import EventSourceResponse
app = FastAPI()
@app.post("/progress", response_class=EventSourceResponse)
async def stream_progress() -> AsyncIterable[dict[str, int]]:
yield {"percent": 25}
```
Yield `ServerSentEvent` to set `event`, `id`, `retry` in milliseconds, or `comment`.
Use `data` for JSON encoding and `raw_data` for literal text, with at most one
payload field per event. Idle streams send a `ping` comment every 15 seconds;
SSE sets `Cache-Control: no-cache` and `X-Accel-Buffering: no`.
FastAPI 0.140.13 honors the route's `status_code` for SSE and JSON Lines streams.
## Frontend serving, routing, and telemetry
Regular path operations take precedence over frontend files, even across routers.
The default `fallback="auto"` selects `404.html` with status `404` when present,
then `index.html` for browser navigation if only that file exists.
The index fallback requires explicit `Accept: text/html` or `application/xhtml+xml`;
a missing asset requested with `Accept: */*` returns `404`.
Only `GET` and `HEAD` are eligible for frontend fallback starting in 0.138.2.
Frontend requests run HTTP middleware and inherit application, router, and
`include_router(..., dependencies=[...])` dependencies. From 0.141.1, their
`BackgroundTasks` run and headers set on the injected `Response` are included.
`check_dir="auto"` defers the directory check in local development with `fastapi dev`.
The default check warns for a missing directory in development and raises during
app creation otherwise; explicit `True` checks at creation and `False` at request handling.
From 0.137.0, routes added after `include_router()` are visible and `router.routes`
can contain nested routers. Use `iter_route_contexts()` for endpoint traversal;
use 0.143.1 or later when reading included-route metadata through it.
Starting in 0.143.0, OpenTelemetry exporters use `OTEL_*` variables only after
opting in with `FASTAPI_OTEL_AUTO_CONFIGURE=true` or
`FastAPI(telemetry={"auto_configure": True})`. FastAPI Cloud enables automatic setup.
Applications can start after automatic configuration failure from 0.142.2.
## Related library migrations
For Starlette 1.0, move startup and shutdown registration to `lifespan=` and use
`Route` and `WebSocketRoute` in `routes=`. Configure middleware and exception
handlers through the `Starlette` constructor. See the reference for template removals.
For SQLModel with Pydantic 2.12 annotated fields, use SQLModel 0.0.32 or newer.
SQLModel 0.0.31 requires Pydantic V2; use `sqlmodel<0.0.31` if V1 is still required.
In embedded Uvicorn launchers, drop removed `Config.setup_event_loop()` calls
and use `await server.serve()` when running inside an existing event loop.