Requests¶
The request object and the parsed containers it exposes.
Request
¶
Incoming HTTP request with lazy attribute parsing.
All expensive operations (JSON parsing, cookie parsing, URL construction, form/multipart parsing) are deferred until accessed — zero overhead for properties you don't use.
Usage::
@app.get("/users/{user_id}")
async def show(request: Request, user_id: str):
data = await request.json()
agent = request.headers.get("user-agent", "")
return {"id": user_id, "agent": agent, "body": data}
query_params
property
¶
query_params: QueryParams
Parse query string lazily - only when accessed.
Repeated keys are preserved: params.getlist("tag") returns every
value; params["tag"] returns the first.
path_params
property
writable
¶
Path parameters captured by the matched route pattern.
view_args
property
¶
Alias for path_params — the matched route's path params.
request.view_args and request.path_params are two names for the
dict of URL-captured values; both point at the same dict.
headers
property
writable
¶
headers: Headers
Return the parsed request headers, materializing from raw ASGI tuples on first access.
referrer
property
¶
Value of the Referer request header.
Spelling preserved from the original RFC misprint (RFC 7231 Sec. 5.5.2
documents Referer, not Referrer). The accessor uses the
corrected spelling so callers don't have to remember.
origin
property
¶
The Origin header - RFC 6454. None when absent.
Set by browsers on cross-origin requests (and all CORS preflights). CORS middleware matches the allow-list against it.
date
property
¶
The request Date header as a tz-aware UTC datetime.
RFC 9110 Sec. 6.6.1 - the originator's timestamp for the message.
Returns None when the header is missing or unparseable.
pragma
property
¶
Value of the legacy Pragma header - RFC 9111 Sec. 5.4.
Almost always no-cache from HTTP/1.0 clients. Returns the
empty string when absent. Prefer cache_control for HTTP/1.1.
max_forwards
property
¶
The Max-Forwards header as an int - RFC 9110 Sec. 7.6.2.
Bounds how many proxies a TRACE/OPTIONS request may traverse.
None when absent or non-numeric.
is_xhr
property
¶
Detect XMLHttpRequest-style AJAX calls.
The convention is X-Requested-With: XMLHttpRequest, set by
jQuery, fetch wrappers, and similar libraries. It's a hint, not
a guarantee (the client controls the header), but it's the
traditional signal application code uses to switch between full
HTML responses and partial / JSON ones.
mimetype
property
¶
Content-Type without parameters.
application/json; charset=utf-8 -> application/json. Lower-cased
and stripped - per RFC 9110 Sec. 8.3 the media type is case-insensitive.
mimetype_params
property
¶
Parameters from Content-Type (e.g. {"charset": "utf-8"}).
Each parameter is key=value; quoted values have their surrounding
double-quotes stripped. Keys are lower-cased; values preserve case.
content_length
property
¶
Return the Content-Length as an integer, or None.
content_encoding
property
¶
Value of the Content-Encoding header.
Returns the lowercased encoding name ("gzip", "br", etc.)
or the empty string when the header is missing.
content_language
property
¶
Value of the Content-Language header - RFC 9110 Sec. 8.5.
Returns the raw header value (a comma-separated list of language tags) or the empty string when the header is absent.
charset
property
¶
Request body charset, decoded from Content-Type.
Defaults to utf-8 when no charset is declared, which is what the
HTTP specifications settled on after moving off ISO-8859-1.
is_json
property
¶
True for application/json or any application/*+json subtype.
Per RFC 6839 Sec. 3.1 the structured-suffix +json (e.g.
application/vnd.api+json, application/problem+json) marks the
body as JSON-encoded.
is_form
property
¶
True when the body is form-encoded or multipart.
That is, application/x-www-form-urlencoded or multipart/form-data.
accept_mimetypes
property
¶
accept_mimetypes: AcceptHeader
Parsed Accept header with MIME wildcard matching.
accept_languages
property
¶
accept_languages: AcceptHeader
Parsed Accept-Language header. q-value ordered.
accept_encodings
property
¶
accept_encodings: AcceptHeader
Parsed Accept-Encoding header (e.g. gzip, br).
auth
property
¶
auth: Authorization | None
Lazy-parse the Authorization: header into a typed object.
Returns None when the header is missing. Basic and Bearer
schemes populate .username/.password and .token respectively;
other schemes carry their key=value parameters in .params.
access_control_request_method
property
¶
CORS preflight Access-Control-Request-Method - RFC 6454.
On an OPTIONS preflight, names the method the real request
will use. None outside a preflight.
access_control_request_headers
property
¶
CORS preflight Access-Control-Request-Headers - header list.
The headers the real request intends to send, lower-cased and whitespace-trimmed. Empty list when the header is absent.
if_modified_since
property
¶
Parse If-Modified-Since (RFC 9110 Sec. 13.1.3) to a Unix timestamp.
Accepts IMF-fixdate, obsolete RFC 850, and ANSI C asctime()
forms. Returns None when the header is missing or unparseable
- never raises, so callers can use it in a single branch.
if_unmodified_since
property
¶
Parse If-Unmodified-Since (RFC 9110 Sec. 13.1.4) to a Unix timestamp.
Returns None when the header is missing or unparseable.
Write-side companion to If-Modified-Since: precondition that
fails with 412 when the resource has been modified since the
given date.
if_match
property
¶
Parse If-Match (RFC 9110 Sec. 13.1.1) into a tuple of ETags.
Returns ("*",) for the wildcard, an empty tuple when the
header is absent, otherwise a tuple of quoted ETags (quotes
and any W/ weak prefix preserved verbatim).
If-Match is the write-side companion to If-None-Match:
precondition that fails the request with 412 Precondition
Failed when none of the listed ETags matches the resource's
current ETag. Standard guard against the lost-update problem.
if_none_match
property
¶
Parse If-None-Match (RFC 9110 Sec. 13.1.4) into a tuple of ETags.
Returns ("*",) when the header is the literal * (matches any
existing representation), an empty tuple when the header is
missing, or a tuple of one or more quoted ETags (the quotes are
preserved so callers can compare them verbatim against an ETag
header on the response).
if_range
property
¶
Parse If-Range: (RFC 9110 Sec. 13.1.5).
The header carries either an ETag or an HTTP-date - never
both. Returns (etag, None) when the value is an ETag (quoted,
possibly weak-prefixed) and ("", timestamp) when it parses as
a date. Returns ("", None) when the header is absent or
unparseable. Caller picks the relevant slot.
Used by GET with Range: to convert a partial-content request
into a full 200 when the cached resource is stale.
range
property
¶
range: RangeSpec | None
Parse the Range: header per RFC 9110 Sec. 14.2.
None when the header is absent or unparseable.
cache_control
property
¶
cache_control: CacheControl
Parsed Cache-Control header.
Returns a CacheControl view: req.cache_control.no_cache
(bool), req.cache_control.max_age (int or None), etc.
Always returns a fresh parse to reflect any header mutation.
cookies
property
¶
cookies: Cookies
Parse cookies from the Cookie header - lazy, MultiDict-shaped.
Returns a Cookies (MultiDict). cookies["name"] gives the first
value; cookies.getlist("name") gives every value when a name
repeats (rare but valid per RFC 6265).
full_path
property
¶
Path + ? + query string.
Always contains a ?, even when the query string is empty.
url_root
property
¶
Root URL of the request: scheme://host/.
Carries the trailing slash, and no path or query string.
scheme
property
¶
Request scheme - "http" or "https".
Sourced from the ASGI scope["scheme"] when present, then from
the X-Forwarded-Proto header (only meaningful behind a trusted
proxy), then default http.
host
property
¶
Value of the Host request header.
Mirrors Request.url.netloc for the common case but pulls
directly from the header to remain cheap (no full URL parse).
Returns the empty string when the header is absent.
root_path
property
¶
The URL prefix the app is mounted under.
Comes from the ASGI server (e.g. uvicorn --root-path /api) or from
app.mount("/sub", inner_app), and falls back to Veloce(root_path=...)
when neither supplies one. That constructor argument is documented as a
way to set the prefix and was read by nothing, so an app configured that
way built unprefixed external URLs and unprefixed slash redirects.
The server wins when it sets one: it knows where the app was actually mounted, and the constructor argument is a declaration made before that is known. The built-in server sets none, which is why the fallback matters there.
Returns the empty string when the app is at root.
script_root
property
¶
Alias for root_path — also called script_root.
ProxyFix-style middleware may also set
_state["proxy_fix_prefix"]; that wins over the ASGI scope
because it represents the trusted outer-edge prefix when the
ASGI server is behind a reverse proxy that strips the prefix.
subdomain
property
¶
Leftmost host label minus app.config["SERVER_NAME"].
Returns the empty string when the request host equals SERVER_NAME
exactly (apex), when SERVER_NAME is not configured and the host has no
dots, or when the host is an IP literal.
Cached: a subdomain-routed request asks twice - once by the router to decide the match, once by the handler to read the value - and it is derived from request data that cannot change. The router asks through this property rather than deriving its own answer, because the two used to disagree.
environ
property
¶
Alias for the ASGI scope dict.
Third-party code paths reach for request.environ (WSGI); ASGI
scope is the analogue. Returns the live dict so middleware can
introspect (mutation goes through framework APIs, not this).
url_rule
property
¶
Return the matched route's template (e.g. /users/{id}).
Returns the raw path template the radix tree used for the match —
i.e. path_params placeholders are unsubstituted. None for
synthetic requests that never went through dispatch.
is_mcp
property
¶
Return whether this request is a replayed MCP tool / resource call.
True when the request was synthesised by the MCP integration to replay a
route through Depends / middleware for an agent call, rather than a real
HTTP request. Authentication middleware that checks a browser credential
(a session cookie, an Authorization header) should return early on these
- the MCP transport authenticates the agent separately. The transport
request itself (POST /mcp) opts such middleware out via
mount_mcp(..., exclude_middleware=[...]).
blueprint
property
¶
Return the name of the blueprint that owns the matched route.
Veloce stores the endpoint as <bp>.<name> for blueprint routes.
Returns the bit before the dot, or None if the endpoint is
unset or is a top-level (no-dot) name.
blueprints
property
¶
Return every blueprint in the matched endpoint's parent chain.
For an endpoint a.b.c.view, returns ["a.b.c", "a.b", "a"]
(innermost first). Empty list when the route is top-level or the
endpoint is unset.
client_host
property
¶
Return the client's IP address, or None when the peer is unknown.
client_port
property
¶
Return the client's port number, or None when the peer is unknown.
client
property
¶
client: Address | None
The connecting peer as an Address(host, port).
request.client.host / request.client.port work, and tuple
unpacking (host, port = request.client) works too. Returns
None when the peer is unknown (e.g. synthetic requests).
Honours ProxyFix - client.host reflects the trusted client IP.
remote_addr
property
¶
Alias for client_host — the connecting client's IP.
Honours ProxyFix-style middleware: when the trusted hop has set
_state["proxy_fix_client"], that value wins over the raw TCP
peer (the ASGI/uvicorn client[0] may be the load balancer).
access_route
property
¶
Forwarded-for chain.
Returns the comma-separated X-Forwarded-For values (client ->
proxy chain order), with the connecting peer (remote_addr)
appended at the end. With no X-Forwarded-For header, returns
[remote_addr] when the peer is known, else [].
RFC 7239 Sec. 5.2 defines the IP-order convention: leftmost is the originating client, rightmost is the closest proxy. Production code should consume the leftmost trusted entry, not blindly the leftmost value.
state
property
¶
state: State
Per-request scratch namespace - ASGI shape.
Supports attribute access (request.state.user = ...) and
dict access (request.state["user"], request.state.get(...)).
session
property
¶
session: Session
Access to the session dict.
SessionMiddleware writes the parsed session into _state["session"]
during process_request; this property is the accessor for it. Raises
RuntimeError when the middleware has not run - which keeps "I forgot
to add SessionMiddleware" from showing up as a confusing silent
empty-dict.
data
property
¶
Raw request body bytes - request.data shape.
The sync-property form of body(). Returns the body exactly as
received, with no decoding or form parsing. Requires the body to
already be buffered; raises RuntimeError otherwise (use
await request.body() for the async path).
max_content_length
property
¶
The body-size cap for this request.
Reads app.config["MAX_CONTENT_LENGTH"] from the bound app
(the dispatcher enforces it, returning 413 on overflow).
None - no limit - when unset or no app is bound.
derive_for_mount
classmethod
¶
derive_for_mount(parent: Request, sub_path: str, body: bytes, sub_app: Any, prefix: str, body_source: Any = None) -> Request
Build the request a mounted sub-app is dispatched with.
The sub-app answers the same connection, so everything the connection
determined - the scheme, the client address, the server, any ASGI
extensions - is carried forward rather than re-declared. Synthesising a
scope holding only root_path is what left request.is_secure reading
False over TLS and request.client_host reading None inside a mount,
and would have dropped every scope-derived property added later too.
Only what the mount itself changes is overridden: the path the sub-app
sees, the root_path that makes its url_for build prefix-correct URLs,
and the now-stale absolute raw_path. This mirrors what _asgi_app
already does for a mounted raw ASGI app.
body_source hands the live body over instead of bytes, for a sub-app
route that streams: only the sub-app knows whether its route does, so
the transport cannot decide before dispatch reaches here.
_length_enforced deliberately stays False: the sub-app is checked
against its own MAX_CONTENT_LENGTH, not its parent's.
url_for
¶
Reverse-resolve a route URL - ASGI shape.
request.url_for("route_name", id=7) delegates to the bound app's
url_for. Raises RuntimeError when the request has no app bound
(synthetic requests built outside dispatch).
With _external=True the absolute URL is built from this request's
origin - the scheme, host and port a trusted ProxyFix recovered - and
carries script_root, so a link generated behind a proxy that
terminates TLS on another port and mounts the app under a prefix points
at the public URL rather than the internal one. app.url_for has no
request to read and falls back to SERVER_NAME. An explicit _scheme
or _host still wins.
get_json
¶
Parse the request body as JSON.
A body whose Content-Type is not JSON raises UnsupportedMediaType
(415) through on_json_loading_failed rather than reading as None, so
a content-type mismatch is reported instead of leaving the caller to
infer it from a missing value. An absent header is not JSON either: a
cross-origin fetch can omit it with no preflight, so a body sent
without one is refused like any other non-JSON body. Pass force=True
to read a body from a client that does not send the header.
force=Trueskips the content-type check entirely, parsing whatever the body holds.silent=TruereturnsNonefor both failures - a refused content type and a malformed body - instead of raising. Default raises so caller code can tell the two apart.cache=Falseforces a re-parse on every call. Default caches the parsed value (one parse per request); cache invalidation is the caller's job whencache=False.
Returns None for empty bodies regardless of force / silent.
The content-type check runs first, so an empty body under a refused
content type still raises.
This is the synchronous accessor: it requires the
body to already be buffered (the in-memory path), and raises
RuntimeError otherwise - reach for await request.json() when
the body has not yet been drained.
on_json_loading_failed
¶
Handle a failure to read the body as JSON on a non-silent request.
error is the decoder error, or None when the request declared a
content type that is not JSON. The two failures answer with different
status codes so a caller can tell them apart: a refused content type
raises UnsupportedMediaType (415), a malformed body BadRequest
(400).
Raises BadRequest (400) with a stable, body-independent message so a
malformed body cannot leak decoder internals (byte offsets derived from
attacker-controlled input) into the production response. The verbose
decoder reason is always logged and attached as BadRequest.debug_detail
for operators, and is surfaced in the response only when debug mode or
the JSON_ERRORS_VERBOSE config flag is set. Override on a Request
subclass to customise.
body
async
¶
Return the full request body as bytes, draining the source once.
Async to match the ASGI convention. Veloce buffers the body before dispatch, so no I/O happens inside the await - the coroutine resolves immediately with the cached bytes.
json
async
¶
Parse the request body as JSON, async to match the ASGI convention.
Veloce buffers the body at construction time, so no I/O actually
happens inside the await - the coroutine resolves immediately
with the cached parse. The async signature exists so the
await request.json() idiom does not blow up at runtime.
A body whose Content-Type is not JSON reads as None rather than
being parsed, which is what stops a cross-origin text/plain send from
driving a JSON endpoint. An absent header is not JSON either, and is
refused the same way: a fetch whose body is a Blob typed "" sends
no header at all, with no preflight to stop it.
The synchronous request.get_json() accessor is available for callers
that prefer a sync API. It applies the same rule but reports a refused
content type as UnsupportedMediaType (415) instead of None; this
door keeps the None so a caller reading the body itself can fall
through to another representation.
get_data
async
¶
Return the raw request body, draining the source once.
Async to match body() / json() / form().
as_text=Truedecodes via theContent-Typecharset (default UTF-8). Falls back tolatin-1when the declared charset is unrecognised - a defensive fallback, since latin-1 round-trips arbitrary bytes without raising.cacheis accepted and ignored. A non-streaming route has its body buffered before the handler runs, so there is nothing to decide; astream=Trueroute is consumed throughrequest.stream()rather than here. The parameter is kept so callers passingcache=Falsefor cross-framework compatibility keep working.
Returns bytes (default) or str (with as_text=True).
files
async
¶
files() -> FormData
View of uploaded files only - a FormData subset.
Parses the form (via form()) and returns a FormData
containing just the entries whose value is an UploadFile.
Non-file form fields are excluded. Empty FormData for
non-multipart requests. Result is cached after first parse.
values
async
¶
Merge the query string and form body - the request.values shape.
Returns a fresh MultiDict with query-string entries first,
then form-body entries appended. Both source MultiDicts
preserve repeated keys; merging preserves the order across
both sources. Form parsing is async (multipart may need
executor reads), so this is an awaitable rather than a property.
is_disconnected
async
¶
Whether the client has gone away.
Answers for a handler that is still streaming its response - the SSE and
long-poll case - as well as for a stream=True request body. On an ASGI
server the receive channel is polled, without blocking and without
consuming a message. Once the answer is True it stays True.
On the native transport a streaming handler does not observe this.
connection_lost records the drop and then cancels the task serving
the request in the same callback, so the handler's next resume raises
CancelledError at the point it would have polled. The handler does
stop producing for a client that is gone - that part works - but
through cancellation rather than through this method, so write the
cleanup in a finally rather than behind an is_disconnected() check
if the native server is the target.
stream
async
¶
Async-iterate the request body in chunks - ASGI shape.
Streamed requests (raw HTTP/1.1) yield each chunk as the socket
delivers it, so async for chunk in request.stream(): ... processes
a large body incrementally without ever buffering it whole. For
in-memory requests (TestClient / ASGI) the buffered bytes are sliced
into 64 KiB chunks instead.
A streamed body is consume-once: nothing is retained as it passes, so a
later request.body() on a stream=True route sees an empty body
rather than a copy the route asked not to keep.
URL
¶
Parsed URL with component access - lazily constructed.
from_request
classmethod
¶
from_request(headers: Mapping[str, str], path: str, query_string: str, scope_scheme: str | None = None, forwarded_port: int | None = None, trust_forwarded_proto: bool = True) -> URL
Construct a URL from request headers and path components.
trust_forwarded_proto is False once ProxyFix has run, which writes
the scheme it trusted into the scope; reading the raw header afterwards
would let a hop it refused set the scheme anyway. With no ProxyFix
installed the header remains a convenience default.
forwarded_port is the public port a trusted reverse proxy supplied. A
port embedded in the Host header always wins, so forwarded_port only
fills one in when the Host header carries none.
Headers
¶
Bases: _GetListMixin, CIMultiDict[str]
Case-insensitive, multi-value header collection.
Backed by multidict.CIMultiDict. headers["X"] returns the first value;
headers.getlist("X") returns all of them. Construction from a plain dict,
a list of tuples or another multidict all work.
getlist
¶
Return all values for the given key as a list. Empty list if absent.
to_wsgi_list
¶
Return headers as a list of (name, value) tuples.
Preserves insertion order and every duplicate.
add
¶
Append a header, with optional key=value parameters.
headers.add("Content-Disposition", "attachment", filename="x.txt")
emits attachment; filename="x.txt". Parameter values
containing whitespace or punctuation are double-quoted.
Underscores in parameter names map to hyphens.
QueryParams
¶
Bases: _GetListMixin, MultiDict[str]
Multi-value, case-sensitive query parameter collection.
Backed by multidict.MultiDict. Repeated query keys (?x=1&x=2)
preserve every value; getlist("x") returns ["1", "2"] while
params["x"] returns "1" (the first).
getlist
¶
Return all values for the given key as a list. Empty list if absent.
from_query_string
classmethod
¶
from_query_string(query_string: str) -> QueryParams
Parse a=1&b=2&a=3 into a multi-value mapping.
Keeps blank values (a=) and decodes percent-escapes; repeated keys
stay in the order the URL carried them.
Cookies
¶
Bases: _GetListMixin, MultiDict[str]
Cookie collection parsed from the Cookie header.
Built on multidict.MultiDict. Parsing delegates to iter_cookies
(RFC 6265 Sec. 5.4), which percent-decodes values and collapses a duplicate
name to its first occurrence.
getlist
¶
Return all values for the given key as a list. Empty list if absent.
State
¶
Bases: dict[str, Any]
Per-request scratch namespace - supports both styles.
A dict subclass whose attribute access maps to items, so
request.state.user and state["user"] / state.get("user") are
interchangeable. The dispatcher also stashes framework internals
(session, url_rule, ...) here by key.
Address
¶
Bases: NamedTuple
Client/server address - ASGI shape.
A two-field named tuple so request.client.host /
request.client.port work, while host, port = request.client
unpacking also works (tuple semantics).
FormData
¶
Bases: _GetListMixin, MultiDict[Any]
Multi-value form-field collection (text fields + file uploads).
Backed by multidict.MultiDict. Repeated form fields (<input name="a">
submitted twice, or repeated multipart parts with the same name)
preserve every value; single-value access form["a"] returns the first.
getlist("a") returns the full list.
getlist
¶
Return all values for the given key as a list. Empty list if absent.
get_upload
¶
get_upload(key: str) -> UploadFile | None
Return the first value if it is an UploadFile, else None.
UploadFile
¶
Uploaded file with an async read/write interface.
content
property
¶
Return the full file content as bytes.
Synchronous: for an upload spooled to disk the underlying read()
blocks, so prefer await read() in an async context.
save
¶
Stream this upload into destination.
destination is a filesystem path (str), opened "wb" and closed
afterwards, or an already-open binary file the caller still owns.
buffer_size bounds memory while streaming. The read cursor is reset to
0 and restored afterwards, so the upload stays available.
This opens and writes on the calling thread; in an async handler use
save_async, which is the same work hopped to a thread.
save_async
async
¶
Stream this upload into destination without blocking the event loop.
The async counterpart of save, with identical behaviour.
AcceptHeader
¶
Parsed Accept-* header with RFC 9110 Sec. 12.5 q-value semantics.
Construction is via AcceptHeader.parse(raw, mime=False). mime=True
enables MIME-style wildcard matching (text/*, */*) used by
Accept; defaults to plain string equality used by Accept-Language,
Accept-Encoding, Accept-Charset.
parse
classmethod
¶
parse(raw: str, mime: bool = False) -> AcceptHeader
Parse a comma-separated header into (value, q) tuples.
A missing or unparseable q-value defaults to 1.0 (RFC 9110
Sec. 12.4.2). An entry with q=0 is kept, because best_match treats
it as an explicit rejection. For MIME headers the media-type parameters
are retained and participate in matching (RFC 9110 Sec. 12.5.1).
quality
¶
Return the q-value the client assigned to value.
For MIME headers, matches */* and type/* wildcards as well as
parameterized media ranges; the MOST SPECIFIC matching client range wins
(RFC 9110 Sec. 12.5.1), ties broken by the higher q-value. Returns 0 for
a value that is rejected or not mentioned.
quality_explicit
¶
Return the q-value for value, with explicit tokens overriding *.
RFC 9110 Sec. 12.5.3: an explicit q=0 means "not acceptable" and must
override a more permissive wildcard, which quality() does not do - it
reports the MAX, so br;q=0, *;q=1 gives br 1.0. This variant prefers
an EXACT token match and falls back to the * q only for a value not
explicitly listed. Non-MIME (Accept-Encoding) semantics.
accepts_identity
¶
Whether the identity (no-encoding) coding is acceptable per RFC 9110.
RFC 9110 Sec. 12.5.3: identity is acceptable by default. It is
UNacceptable only when an explicit identity entry carries q=0, or
when it is unlisted and a * entry carries q=0. Token comparison is
case-insensitive (Sec. 8.4.1).
best_match
¶
Return the option the client accepts with the highest q-value.
Among candidates the client accepts (q>0), the one whose best matching
range has the highest (q, specificity) wins, so a parameterized exact
match beats a bare wildcard (RFC 9110 Sec. 12.5.1); ties go to the order
in options. Returns default when no option has q>0, and options[0]
for an empty header, since a missing Accept means "accept anything".
Authorization
¶
Parsed Authorization header.
Two common shapes are first-class:
- Basic (RFC 7617): .type == "basic", .username + .password set.
- Bearer (RFC 6750): .type == "bearer", .token set.
Other schemes (Digest per RFC 7616, Negotiate, custom) populate .params
with the comma-separated key="value" parameters parsed from the credentials
portion; .type is the scheme name lower-cased.
Authorization.from_header(value) returns None for empty or malformed
input rather than raising.
from_header
classmethod
¶
from_header(header_value: str) -> Authorization | None
Parse an Authorization: header value. Returns None on miss.
RangeSpec
¶
Parsed Range: header (RFC 9110 Sec. 14.2).
unitis the range unit, e.g."bytes"(the only commonly-used one).rangesis a list of(start, end)tuples, withNonestanding in for an open endpoint:0-499->(0, 499)1000-->(1000, None)(open at the right)-500->(None, 500)(suffix-range - last 500 bytes)
The remaining header helpers are reached through the veloce.http gateway:
they parse or build a header value rather than describing a Request
attribute.
CacheControl
¶
Parsed view of a Cache-Control header.
to_header
¶
Serialise back to a Cache-Control header value.
Preserves source-observed order; user-set directives append in set order.
HeaderSet
¶
Ordered, case-insensitive set of header tokens.
For headers like Vary and Allow that carry a comma-joined token list.
Lookup ignores case; iteration and to_header() keep insertion order.
update
¶
Add every header in headers, ignoring ones already present.
parse_multipart_form
¶
parse_multipart_form(body: bytes, content_type: str, *, max_parts: int | None = DEFAULT_MAX_MULTIPART_PARTS, max_files: int | None = None, max_fields: int | None = None, max_part_size: int = DEFAULT_MAX_MULTIPART_PART_SIZE, max_file_size: int | None = None, max_field_size: int | None = None, max_field_memory: int | None = None, charset_fallback: str | None = None) -> FormData
Parse multipart/form-data into FormData with UploadFile support.
max_parts caps the total number of parts; None disables the cap,
matching what MAX_FORM_PARTS = None means for a urlencoded body.
max_files and max_fields cap file and text-field parts independently.
max_part_size caps each part's body size, and max_file_size /
max_field_size override it per part kind. max_field_memory caps the
cumulative resident bytes of all text fields, value plus field-name bytes -
a ceiling max_field_size alone cannot express.
Exceeding any limit raises RequestEntityTooLarge (413), so a maliciously
structured form cannot exhaust memory or CPU within MAX_CONTENT_LENGTH.
A missing boundary, or one violating the RFC 2046 grammar, raises
BadRequest (400) rather than silently yielding an empty form.
charset_fallback handles non-UTF-8 field bytes where a part declares no
charset: the default None rejects them with BadRequest (400), while
"replace" substitutes U+FFFD and "latin-1" decodes as ISO-8859-1. A part
declaring its own charset (RFC 7578 Sec. 5.1.2, one of ascii, us-ascii,
utf-8, iso-8859-1) is decoded strictly with it, so invalid bytes raise
BadRequest rather than being corrupted.
header_key
¶
Return the actual stored key matching name case-insensitively, or None.
Pass name in its canonical casing. Use the returned key to rewrite a
value in place under whatever casing the caller originally stored.
header_get
¶
Return the value stored under name case-insensitively, or None.
header_present
¶
Return True when a header named name exists under any casing.