Documentation

Docs / Reference

Claim contract: FastAPI route shape

ADR 0081 (Accepted), section "Shape model"; the model rows SM-* are in the route shape claim contract. Rows SH-F1..SH-F39 and the default row D say which FastAPI and Starlette code forms the FastAPI shape extractor reads, what each claims and when it refuses. The Go table routes.FastAPIShapeContract (internal/extract/routes/fastapi_shape_contract.go) lists the same rows in the same order with the same forms; TestFastAPIShapeContract keeps the two 1:1 and TestFastAPIShapeFixture checks that the fixtures testdata/fixtures/route-shape-fastapi, route-shape-fastapi-handlers, route-shape-fastapi-unpack and route-shape-fastapi-assign reach every row. Every stored item names its row in provenance.rule.

Semantics follow FastAPI 0.161.1 and Pydantic 2.14.2 (the oracle in scripts/oracle/fastapi_shape.sh: FastAPI's app.openapi() and a TestClient run that reaches every stated status, validates success bodies against the stated schemas and checks every stated required body field). Behaviour that depends on the FastAPI version is stated only when the nearest pyproject.toml that requires fastapi (or fastapi-slim) proves the version with a lower bound (>=, ==, ~=, > in project.dependencies, or a Poetry constraint, whose || alternatives give their lowest bound); with both sources the lower bound applies. A marker, a direct reference, a pre-release or dev bound, or a [tool.uv] override or constraint naming fastapi proves nothing; then the weaker claim applies. The extractor reads cached syntax (gate SG: files that import fastapi, starlette, pydantic or sqlmodel) at link time; a function in any other file is a proven target whose body is not read (resolver_error, the sections stay partial).

Vocabulary

Claim contract

Row Title Forms Claim Refused
SH-F1 path parameter declared path name annotation, Path() A handler or dependency parameter named like a template parameter, or with Path(), is a path parameter: fact, required, schema from the annotation. Path() naming no template parameter, a non-scalar annotation: D.
SH-F2 path parameter from the template only {name}, {name:convertor} A template parameter no parameter declares is still matched by Starlette: fact, required; schema string (str, path, uuid, none), integer (int) or number (float). FastAPI's spec omits it. Any other convertor, or a dependency tree not fully read: schema null and the section partial.
SH-F3 path section state path complete, path provably_none provably_none (no template parameter) or complete (every template parameter has a typed fact item) with the registration as evidence. Prefixes with different parameters, untyped parameters or names read: partial. An unmounted route: not_read.
SH-F4 query parameter from a scalar annotation scalar annotation A parameter without a marker whose annotation is a scalar is a query parameter: fact, required unless it has a default.
SH-F5 Query, Header and Cookie markers Query(), Header(), Cookie(), alias=, convert_underscores= A query, header or cookie parameter: fact; required when the marker has no default (or ...) and, in Annotated, when the parameter has none. Name: a literal alias, else the parameter name, with _ turned into - for a header unless convert_underscores=False. A non-literal alias, validation_alias, serialization_alias, include_in_schema, a model type with Query(): D.
SH-F6 parameter without annotation no annotation A query parameter (path when the template names it): fact, schema unknown ("any value").
SH-F7 Annotated aliases X = Annotated[...] A module-level Annotated alias is resolved before classifying, so SessionDep is a dependency and TokenHeader a header (H5). An alias in another form: D.
SH-F8 enum and Literal types Enum subclass, Literal[...] An Enum subclass with literal members, or Literal[...] of literals, is an enum schema of its values. A member that is not a literal (auto()), an enum defining _missing_ (other values validate): unknown.
SH-F9 dependency function parameters Depends(function), Security(function) A proven repository function is followed (value dep); its parameters are classified like the handler's and carry the chain (H2: a dependency parameter named like a template parameter is a path parameter). Unresolved, ambiguous, external, a lambda or another expression: a stop, every parameter section partial.
SH-F10 dependency class with init Depends(Class) A repository class with its own __init__ is followed into __init__ (without self). A class without its own __init__ (a Pydantic model, a dataclass): unresolved stop.
SH-F11 OAuth2 password request form OAuth2PasswordRequestForm, OAuth2PasswordRequestFormStrict Depends() on FastAPI's form class adds its form fields (username, password required; grant_type, scope, client_id, client_secret optional; strict: grant_type required) to an application/x-www-form-urlencoded body (H4).
SH-F12 dependencies= lists route dependencies=, router dependencies=, include_router dependencies=, app dependencies= Their Depends items are followed like parameters (H8): their parameters join the route's. An item that is not a Depends call, a non-literal list, keyword unpacking: every parameter section partial.
SH-F13 security scheme dependency Depends(scheme instance), Depends(subclass instance) An instance of a fastapi.security class itself adds no parameter; it is read by SH-F32/SH-F33. An instance of a repository subclass is a dependency on its own __call__ (found in the class or its repository bases), followed like SH-F9 without self: FastAPI calls it, so its reads and raises are the route's. A repository subclass without a __call__ read: an unresolved stop, every parameter section partial.
SH-F14 framework values Request, WebSocket, HTTPConnection, Response, BackgroundTasks, SecurityScopes Classified by annotation, never by name (H6): no parameter. A request value is followed (SH-F15..SH-F17).
SH-F15 names read on the request request.headers, request.cookies, request.query_params, request.path_params A literal key read with [...], .get() or .getlist() is a parameter of kind read_in_handler, presence unknown, no schema; read_by_dependency when a dependency (or a function it calls) reads it (H3), else read_by_handler. The section is partial. A key that is not a literal, another method: the section partial.
SH-F16 raw body reads request.json(), request.body(), request.form(), request.stream() A body item of kind read_in_handler, content type and schema null; the body section is partial.
SH-F17 request object passed on f(request), f(request.headers) A proven call receiving the request value (or its mapping) is followed with the callee's parameter. Reading base_url, client, app, method or url_for is not a use. Any other use of the value (request.url, request.state, stored, iterated, passed to a builtin or to *args/**kwargs), an unproven call: the sections it can reach are partial. A request parameter reassigned is such a use, and its reads after the assignment are not recorded (they read another value).
SH-F18 single body parameter model annotation, Body() One body parameter without embed: the body is its schema, application/json (or a literal media_type).
SH-F19 embedded body several body parameters, Body(embed=True) Several body parameters or embed=True: an object with one field per parameter (name, presence, schema).
SH-F20 form and file bodies Form(), File(), UploadFile, list[UploadFile], Annotated[Model, Form()] Form fields: an object, application/x-www-form-urlencoded; with a file (UploadFile, `UploadFile Noneand sequences of them are file fields without a marker, as FastAPI'sanalyze_param): multipart/form-data. A single Form()parameter typed with a model is read as the model's fields (FastAPI 0.113.0 and later, proven from the manifest): the body schema is the model's,application/x-www-form-urlencoded`.
SH-F21 sequence or mapping without a marker list[T], set[T], dict[K, V] A sequence or mapping annotation without a marker is a body parameter, never a query parameter (H1).
SH-F22 repository models BaseModel subclass, SQLModel subclass, Field(), model_config extra, pydantic version A repository class reaching pydantic.BaseModel or sqlmodel.SQLModel (not a table class) is a model of kind fact: its annotated fields (repository model bases first), presence from the default (Field(default=...), default_factory, a value; ... is required; no default is required, but for a field whose type accepts None (Optional[T], `T None) or is not read only when the nearest pyproject.tomlrequiringpydanticdirectly proves every allowed install is 2 or later, read like the FastAPI version of SH-F26: Pydantic 1 gives such a field a None default, so without that proof its presence isunknown), a literal aliasas the name,extra="forbid"/"allow"asadditional; Relationship()andClassVarare not fields.Annotatedmetadata (at any depth, in fields and parameters) keeps the type only when it is a literal,annotated_typesconstraints,StringConstraints, AfterValidatororDoc`.
SH-F23 parameter and body section state complete, provably_none When the dependency tree and every request value were read with nothing missing: provably_none (no item) or complete (only fact items), with the handler as evidence. Anything missing: partial with the reasons.
SH-F24 success status and content type status_code=, default 200, response_class=, default_response_class=, **options, x.default_response_class = C, no-body status, returned Response, Response parameter The success status: a literal or status.HTTP_* constant; without one, the response class's own default (RedirectResponse 307, the other FastAPI/Starlette classes 200; FastAPI passes no status); content type application/json, or that of a FastAPI/Starlette response_class. A status below 200, 204 or 304 has no body (schema null, no content type). This is the status FastAPI sends when the handler returns, never a claim that it returns. The success item is fact only when every return of the handler is proven not to be a Response (FastAPI sends one as is): a literal, container or builtin conversion, a typed parameter, a model or enum constructor, jsonable_encoder(...), a proven function annotated with another type, or an unannotated proven function whose returns are proven the same way (up to the depth limit); otherwise intended with the reason. A Response parameter whose status is set (or that is used otherwise or passed on) lowers it too; set_cookie, delete_cookie and header writes do not. A non-literal status, a response class not read, or (without status_code=) an inherited default response class whose default status is not 200 or is not read: partial, no success item. Another response class, or any inherited default response class: content type null. A route inherits the default_response_class (or keyword unpacking, which may pass one) of the APIRouter or FastAPI it is registered on, of every include_router call that includes that router, directly or through other routers, and of every including router or app, as FastAPI 0.161.1 resolves it; a Starlette mount passes none on, and objects the route's router is not included into do not affect it. An include_router call whose including object is not read passes on every default response class of the project. Any x.default_response_class = ... assignment in the project (the object and the order are not modelled) makes every route's default success status and content type not read.
SH-F25 response_model response_model=T The success response's schema is T's (fact; the decorator overrides the return annotation, H7).
SH-F26 return annotation -> T Without response_model, the return annotation is the success response's schema: fact when the manifest proves FastAPI 0.89.0 or later (FastAPI validates and filters the returned value with it), else returned. SH-F24's Response exclusion and SH-F36 apply.
SH-F27 no response model response_model=None, -> None, -> Response, no return annotation The success response with schema unknown and the reason.
SH-F28 responses= dictionary responses={code: {...}} Each literal key (a code, a range, default, a status constant) is a response of kind intended (documented, not checked); a model key gives its schema and application/json. A non-literal dictionary, key or value: partial.
SH-F29 raised HTTPException raise HTTPException(status_code=n) A raise of FastAPI's or Starlette's HTTPException in the handler, a dependency or a followed function is a response with that status, fact, content type and schema null, with the chain. FastAPI's spec does not list these. SH-F37 can lower it to intended. Inside a try body, or reached through a call inside one: not stated (partial). After the function's first yield (in source order; in a dependency it runs after the response is sent): not stated. A non-literal status, a repository exception class: partial.
SH-F30 validation error response 422 A route with a declared parameter or body has FastAPI's 422 response with its HTTPValidationError model: fact when some declared item can fail validation (a required query, header, cookie or form item, a JSON body, a typed or constrained item: not str, bytes, Any, SecretStr, Path or an unannotated one), else intended (documented by FastAPI, not reachable). SH-F37 can lower it to intended.
SH-F31 returned values followed return f(...), x = f(...); return x, return Model(...) Without a response model or return annotation, the handler's returned call is followed through proven functions to a return annotation or a model constructor: a response of kind returned beside the success response; several different types: unknown. Any other returned value, an unproven call: partial.
SH-F32 security schemes OAuth2PasswordBearer, APIKeyHeader, APIKeyQuery, APIKeyCookie, HTTPBearer, HTTPBasic, HTTPDigest, OpenIdConnect A scheme from the route's security chain facts (rows DA-F3) with its name and every field its type needs: the key name and its location, bearer/basic/digest and a literal bearerFormat, openIdConnectUrl; for FastAPI's own OAuth2PasswordBearer the scheme is stated with tokenUrl when it is a literal or module constant, else token_url null (a detail not read, SM-19). A repository subclass of a scheme class (its own code decides what is read), a settings default or computed value of another field, an unknown scheme name, OAuth2AuthorizationCodeBearer or OAuth2 (fields the model lacks), keyword unpacking, two schemes with one name: no scheme, the section partial.
SH-F33 security requirement security_dependencies One requirement holding every stated scheme of the route (they all run): fact when every scheme has auto_error=True, else intended. The section is partial (middleware is not read). Security(..., scopes=...) anywhere in the tree, an unknown security entry: no requirement or partial. No security dependency: not_read (never "public").
SH-F34 hidden routes include_in_schema=False The shape is extracted like any route; the flag only hides it from FastAPI's spec.
SH-F35 call following proven call, stop Calls are followed only to a unique repository definition, up to index.shape_depth; every chain is stored with its depth and stop (model rows SM-21..SM-29).
SH-F36 response model options response_model_include=, response_model_exclude=, response_model_exclude_none=, response_model_by_alias=, response_model_exclude_unset=, response_model_exclude_defaults= response_model_include, response_model_exclude (not None), response_model_exclude_none (not False) or response_model_by_alias (not True) make the success schema of SH-F25/SH-F26 unknown: fields may be left out or renamed. exclude_unset and exclude_defaults drop only fields with a default, which are optional already: no change. Keyword unpacking on the decorator: unknown.
SH-F37 project exception handlers exception_handler(K), add_exception_handler(K, h), exception_handlers=, FastAPI(**options) Any registration in the project (an app object can be configured anywhere), and any FastAPI constructor with keyword unpacking (it may pass exception_handlers, a key not read): a handler for FastAPI's or Starlette's HTTPException lowers every SH-F29 item to intended, one for a status code those with that status; a handler for RequestValidationError, ValidationException or pydantic's ValidationError lowers the SH-F30 item; a key not read lowers both. Handlers for builtin exceptions or repository classes do not catch these (Starlette looks the handler up along the raised class's MRO).
SH-F38 custom route classes route_class=, APIRouter(**options), x.route_class = C A route registered on an APIRouter whose route_class is not fastapi.routing.APIRoute (or keyword unpacking on its constructor), or any project that assigns route_class, has every fact of its parameter, body and response sections lowered to intended (required presence to unknown) and those sections partial: the route class can rewrite the request and the response. The route class is the registering router's own: an including router's route_class does not apply to included routes, and FastAPI takes no route_class (keyword unpacking on it does not lower).
SH-F39 streamed handlers yield, -> Iterable[T] A handler whose body yields, or whose return annotation is an Iterable, Iterator, Generator or async form: the success item is intended, content type null and schema unknown (FastAPI streams the values, as JSON Lines in recent versions; the format depends on the version).
D every other form Not stored: the sections it can reach are partial with the reason, or stay not_read.

Report a problem with this pageSource: docs/contract/claims/route-shape-fastapi.md