Skip to content

API reference

The public surface, generated from the source. Semantics follow the Fetch / URL / URLPattern standards; spelling follows PEP 8 (searchParamssearch_params, getSetCookie()set_cookie_list()).

Application

The application: routing, middleware, and the runtime-agnostic fetch() core.

routes property

Every registered route in registration order (read-only).

The introspection surface for tooling (OpenAPI generation, route listings): each Route exposes method, pattern, handler, and middleware. Mutating the tuple does not affect routing.

ws(path)

Register a WebSocket route: async def handler(c, ws).

use(arg, middleware=None)

use(arg: M, middleware: None = None) -> M
use(arg: str, middleware: M) -> M
use(arg: str, middleware: None = None) -> Callable[[M], M]

Register middleware, optionally scoped to a URLPattern.

Forms: app.use(mw), @app.use, app.use("/admin/*", mw), and @app.use("/admin/*").

fetch(request, env=None, ctx=None) async

Handle one request. The only entry point; everything else adapts to it.

Background work (c.wait_until): with an explicit ctx the caller owns draining it (Workers-style). Without one, pending work rides on the returned response and is drained by the adapter or app.request() after the response is delivered.

request(path='/', *, method='GET', headers=None, body=None, json=None) async

Call the app directly — no server, no adapter. The primary test API.

Context

The one object handlers and middleware receive: request, env, and response helpers.

wait_until(awaitable)

Run work after the response is sent (Workers ctx.waitUntil).

header(name, value, *, append=False)

Stage a header for the final response (merged after the chain runs).

event_stream(source, status=200, headers=None)

Server-Sent Events response (WHATWG HTML Standard).

Stage a Set-Cookie header (RFC 6265bis attributes as kwargs).

Requests

Bases: Body

Fetch Request: URL, method, immutable headers, one-shot body, abort signal.

The routed request handed to handlers as c.req.

Wraps the standard Request (available as .raw) and adds server-side context: route parameters and query helpers. The standard surface (method, url, headers, body readers) is delegated unchanged. Route parameter values are percent-decoded; raw values are available via the URLPattern result if ever needed.

valid(target)

Validated data stored by the validator middleware.

Responses

Bases: Body

Fetch Response: status, headers, and a one-shot body.

Adapters translate it to whatever each runtime speaks.

Bases: Exception

Raise anywhere in a handler or middleware to produce an error response.

Build an RFC 9457 application/problem+json response.

Member names mirror the RFC ("type" defaults to "about:blank" by omission). extensions become extension members.

Cookies

Parse a Cookie request header. First occurrence wins.

Serialize one Set-Cookie header value (RFC 6265bis).

Enforces the spec's structural rules up front: valid name/value octets, SameSite=None requiring Secure, and the __Host-/__Secure- prefix preconditions.

Primitives

Fetch Headers: case-insensitive multimap with guard semantics.

set(name, value)

Replace the first occurrence, drop the rest (Fetch set).

get(name)

Combined value per Fetch: multiple values joined with ", ".

All set-cookie values, uncombined (Fetch getSetCookie()).

raw()

Underlying (name, value) pairs in insertion order, for adapters.

WHATWG URL — the documented subset measured in docs/conformance.md.

WHATWG URLSearchParams over the query string.

Pattern matcher for URL pathnames (subset of the URLPattern standard).

Fetch AbortSignal: observable cancellation state for a request.

add_listener(callback)

Register an abort callback (fires immediately if already aborted).

raise_if_aborted()

Fetch throwIfAborted().

Realtime

A server-side websocket connection.

send / receive / close, plus async iteration over incoming messages.

accept() async

Complete the handshake (idempotent; the adapter calls this).

receive() async

Next message from the client; raises WebSocketClosed on disconnect.

Bases: Exception

Raised by receive() once the client has disconnected.

Validation

Request validation hook (DESIGN.md §9.2).

The core stays dependency-free: validator(target, validate) accepts any callable that turns raw data into a validated value (or raises). Schema libraries plug in directly — no adapter package needed:

import msgspec

class BookIn(msgspec.Struct):
    title: str

@app.post("/books", validator("json", lambda data: msgspec.convert(data, BookIn)))
async def create(c):
    book = c.req.valid("json")   # BookIn instance

# pydantic works the same way:
#   validator("json", TypeAdapter(BookIn).validate_python)

Targets: json (parsed body), form (urlencoded/multipart fields, last value wins), query (search params, last value wins). Failures become RFC 9457 problem responses (400) with the validator's message as detail.

validator(target, validate)

Middleware that validates a request target with any callable.

msgspec.convert and pydantic's TypeAdapter(...).validate_python plug in directly. Handlers read the result via c.req.valid(target).

Deferred work

Deferred work that must complete after the response is sent.

Mirrors the Workers ExecutionContext: wait_until() schedules an awaitable, and the active adapter drains the scheduled work after the response has been delivered. When app.fetch() is called without an explicit context (tests, embedding), it drains before returning.