httk.serve.http.openapi

A constrained, offline OpenAPI 3.1 adapter for Starlette.

Submodules

Attributes

ResponseHook

A zero-argument coroutine callback run once, after the response has been sent.

ServeApp

The httk-serve serving application type (a Starlette app; branded so consumers need not import Starlette).

ExceptionHandler

RequestErrorHandler

RequestScope

Exceptions

OpenAPIContractError

Report an unsupported or internally inconsistent OpenAPI contract.

OpenAPIRequestError

Report adapter-generated request parsing or validation failure.

OpenAPISchemaError

Report an unavailable or invalid JSON Schema document.

Classes

OpenAPIOperation

Describe one supported OpenAPI operation.

OpenAPIParameter

Describe one supported string OpenAPI parameter.

OpenAPIRequest

Normalized values passed to an OpenAPI operation handler.

OpenAPIResponse

A handler response constrained by the matched OpenAPI operation.

BoundOperation

A validated binding of one operation to its resolved handler callable.

BoundParameter

Describe where one handler parameter's value is resolved from per request.

OperationBinding

Declare how one operation's declared inputs bind to a handler callable.

OperationContext

Carry per-request values between a request scope and one operation handler.

OpenAPIContract

Bundle a parsed OpenAPI contract with its offline JSON Schema registry.

OpenAPISchemaRegistry

Validate caller-supplied JSON Schema documents without network retrieval.

Functions

create_openapi_app(contract, operations, *[, ...])

Create a Starlette app from a constrained OpenAPI 3.1 contract.

parse_openapi_operations(document)

Parse the supported OpenAPI 3.1 path subset.

bind_operation(operation, entry, *[, implementation, ...])

Validate and bind one operation's declared inputs to its handler by name.

convert_result(operation_id, result)

Convert a handler return value into a constrained operation response.

normalize_parameter_name(name)

Normalize an OpenAPI wire parameter name to a Python identifier form.

operation(target, *[, aliases, extras])

Declare an operation binding with optional aliases and request-scope extras.

load_packaged_contract(package, *path)

Load an OpenAPI contract from package data without network access.

packaged_schema_documents(package, *path)

Load every bundled JSON Schema document below a package resource.

packaged_schema_registry(package, *path)

Build an offline schema registry from bundled JSON Schema documents.

Package Contents

type httk.serve.http.openapi.ResponseHook = Callable[[], Awaitable[None]][source]

A zero-argument coroutine callback run once, after the response has been sent.

type httk.serve.http.openapi.ServeApp = Starlette[source]

The httk-serve serving application type (a Starlette app; branded so consumers need not import Starlette).

Annotation-only: this is a type alias, not the Starlette class, so use Starlette itself for isinstance/subclass checks.

type httk.serve.http.openapi.ExceptionHandler = Callable[[Exception, 'OpenAPIRequest'], 'OpenAPIResponse | Awaitable[OpenAPIResponse]'][source]
exception httk.serve.http.openapi.OpenAPIContractError[source]

Bases: ValueError

Report an unsupported or internally inconsistent OpenAPI contract.

class httk.serve.http.openapi.OpenAPIOperation[source]

Describe one supported OpenAPI operation.

Parameters:
  • method – Lowercase HTTP method.

  • path – OpenAPI path template.

  • operation_id – Unique operation identifier.

  • parameters – Supported path, query, and header parameter contracts.

  • request_schema – Required JSON request schema identifier, if any.

  • responses – Exact status, media type, and schema response contracts.

  • success_status – The single declared 2xx status, or None when the operation declares zero or more than one.

method: str
path: str
operation_id: str
parameters: tuple[OpenAPIParameter, Ellipsis]
request_schema: str | None
responses: collections.abc.Mapping[int, tuple[tuple[str | None, str | None], Ellipsis]]
success_status: int | None
property success_contracts: tuple[tuple[str | None, str | None], Ellipsis]

Return the media type and schema contracts declared for the success status.

Returns:

The declared (media type, schema id) pairs for success_status, or an empty tuple when there is no single declared success status.

Return type:

tuple[tuple[str | None, str | None], Ellipsis]

response_contracts(status)[source]

Return the media type and schema contracts declared for one status.

Parameters:

status (int) – Exact HTTP status to look up.

Returns:

The declared (media type, schema id) pairs for status, or an empty tuple when the status is not declared.

Return type:

tuple[tuple[str | None, str | None], Ellipsis]

class httk.serve.http.openapi.OpenAPIParameter[source]

Describe one supported string OpenAPI parameter.

Parameters:
  • name – Parameter name as declared by OpenAPI.

  • locationpath, query, or header.

  • required – Whether the parameter must be sent.

  • enum – Optional exact set of accepted string values.

name: str
location: str
required: bool
enum: tuple[str, Ellipsis] | None = None
class httk.serve.http.openapi.OpenAPIRequest[source]

Normalized values passed to an OpenAPI operation handler.

Parameters:
  • operation – Matched OpenAPI operation.

  • path_params – Normalized route parameters.

  • query – Query parameters, retaining Starlette’s last-value semantics.

  • headers – Lowercase HTTP header names and values.

  • body – Validated JSON body, or None for bodyless operations.

operation: OpenAPIOperation
path_params: collections.abc.Mapping[str, str]
query: collections.abc.Mapping[str, str]
headers: collections.abc.Mapping[str, str]
body: Any = None
header(name)[source]

Return one request header case-insensitively.

Parameters:

name (str) – Header name.

Returns:

Header value, if sent.

Return type:

str | None

exception httk.serve.http.openapi.OpenAPIRequestError(operation, detail, request)[source]

Bases: ValueError

Report adapter-generated request parsing or validation failure.

Parameters:
  • operation (OpenAPIOperation) – The matching operation.

  • detail (str) – Human-readable request failure detail.

  • request (OpenAPIRequest) – Partial normalized request values.

operation
detail
request
class httk.serve.http.openapi.OpenAPIResponse[source]

A handler response constrained by the matched OpenAPI operation.

Parameters:
  • status – Exact declared HTTP status, or None to use the matched operation’s declared success status.

  • body – Optional JSON-compatible response body.

  • media_type – Exact declared media type; inferred only when unambiguous.

  • headers – Additional HTTP response headers.

  • after_response – Optional zero-argument coroutine callback run once after the response has been sent.

status: int | None = None
body: Any = None
media_type: str | None = None
headers: collections.abc.Mapping[str, str]
after_response: httk.serve.http.apptypes.ResponseHook | None = None
type httk.serve.http.openapi.RequestErrorHandler = Callable[['OpenAPIRequestError'], 'OpenAPIResponse'][source]
type httk.serve.http.openapi.RequestScope = Callable[['OpenAPIRequest'], contextlib.AbstractAsyncContextManager['OperationContext']][source]
httk.serve.http.openapi.create_openapi_app(contract, operations, *, implementation=None, schemas=None, request_error_handler, exception_handlers=None, request_scope=None, scope_names=(), lifespan=None, debug=False, path_converters=None)[source]

Create a Starlette app from a constrained OpenAPI 3.1 contract.

contract accepts either an OpenAPIContract, which already bundles its offline schema registry, or a plain OpenAPI document mapping paired with a separate schemas registry.

Each operations entry is a bare handler callable or an OperationBinding. The framework binds the operation’s declared path, query, and header parameters, the validated request body, and any whole-request injection to the handler’s parameters by name; see operation().

Parameters:
  • contract (OpenAPIContract | Mapping[str, Any]) – Parsed contract, or a caller-owned OpenAPI path document.

  • operations (Mapping[str, Callable[..., Any] | OperationBinding]) – Operation-id-to-handler mapping.

  • implementation (object | None) – Object whose methods resolve class-defined function entries; None uses each entry callable directly.

  • schemas (httk.serve.http.openapi.schemas.OpenAPISchemaRegistry | None) – Offline JSON Schema registry for external body references. Required and used when contract is a plain mapping; must not be supplied when contract is an OpenAPIContract.

  • request_error_handler (RequestErrorHandler) – Converts request parsing or schema errors to a response.

  • exception_handlers (collections.abc.Mapping[type[Exception], ExceptionHandler] | None) – Exact protocol exception classes converted to responses.

  • request_scope (RequestScope | None) – Optional per-request async context manager entered around each handler call. It populates the OperationContext extras before the handler runs and may set response metadata after it returns; that metadata is folded into the response on normal completion only, never onto an error or adapted-exception response.

  • scope_names (collections.abc.Sequence[str]) – Names of the request-scope values the scope may supply, against which each operation’s declared extras are validated.

  • lifespan (collections.abc.Callable[[httk.serve.http.apptypes.ServeApp], Any] | None) – Optional Starlette lifespan callable.

  • debug (bool) – Whether Starlette debug responses are enabled.

  • path_converters (collections.abc.Mapping[str, str] | None) – OpenAPI path parameter to Starlette converter mapping.

Returns:

Mountable Starlette application.

Raises:

OpenAPIContractError – If the operations or the contract are incomplete or unsupported, if a handler cannot satisfy an operation’s declared inputs by name, or if contract and schemas disagree about which schema registry to use.

Return type:

httk.serve.http.apptypes.ServeApp

httk.serve.http.openapi.parse_openapi_operations(document)[source]

Parse the supported OpenAPI 3.1 path subset.

Local references may be used for path items, operations, parameters, request bodies, and responses. Bodies use external JSON Schema references. Supported parameters are path, query, and header parameters with a simple schema.

Parameters:

document (collections.abc.Mapping[str, Any]) – Caller-owned OpenAPI document mapping.

Returns:

Operations in document order.

Raises:

OpenAPIContractError – If the document uses an unsupported construct.

Return type:

tuple[OpenAPIOperation, Ellipsis]

class httk.serve.http.openapi.BoundOperation(operation, target, sources)[source]

A validated binding of one operation to its resolved handler callable.

Parameters:
property operation_id: str

Return the bound operation’s identifier.

Returns:

The operation id.

Return type:

str

class httk.serve.http.openapi.BoundParameter[source]

Describe where one handler parameter’s value is resolved from per request.

Parameters:
  • param – Handler parameter name that receives the value.

  • kind – Source kind: path, query, header, body, request, or extra.

  • key – Lookup key within the source; the wire parameter name (lowercased for headers) for parameter sources, the scope name for extra, and unused for body and request.

param: str
kind: str
key: str
class httk.serve.http.openapi.OperationBinding[source]

Declare how one operation’s declared inputs bind to a handler callable.

Parameters:
  • target – Callable implementing the operation. A bound method or module-level function is used directly; a plain function defined on a class is resolved against implementation when the application is created.

  • aliases – Wire parameter name to handler parameter name overrides. The reserved wire name body remaps the request body.

  • extras – Names of request-scope values this operation consumes.

target: collections.abc.Callable[Ellipsis, Any]
aliases: collections.abc.Mapping[str, str]
extras: tuple[str, Ellipsis] = ()
class httk.serve.http.openapi.OperationContext[source]

Carry per-request values between a request scope and one operation handler.

The scope populates extras before the handler runs; the framework passes each extra the operation declares to the handler by name. After the handler returns, the scope may set media_type, headers, and after_response, which the framework folds into the response on normal completion only. The context is mutable by design so the scope can both supply inputs and collect response metadata.

Parameters:
  • extras – Request-scope values keyed by the extra name each declares.

  • media_type – Exact response media type the scope contributes, if any.

  • headers – Additional response headers the scope contributes.

  • after_response – Zero-argument coroutine callback the scope contributes to run once after the response has been sent, if any.

extras: dict[str, Any]
media_type: str | None = None
headers: dict[str, str]
after_response: httk.serve.http.apptypes.ResponseHook | None = None
httk.serve.http.openapi.bind_operation(operation, entry, *, implementation=None, scope_names=())[source]

Validate and bind one operation’s declared inputs to its handler by name.

Parameters:
Returns:

The validated per-request binding.

Raises:

OpenAPIContractError – If the handler cannot satisfy the operation’s declared inputs by name.

Return type:

BoundOperation

async httk.serve.http.openapi.convert_result(operation_id, result)[source]

Convert a handler return value into a constrained operation response.

An awaitable is awaited first, so both synchronous and asynchronous handlers are supported. None becomes the bodyless success response, a mapping or list becomes a response body, and an OpenAPIResponse is used as is.

Parameters:
  • operation_id (str) – Operation identifier used in error messages.

  • result (Any) – Raw handler return value or awaitable of one.

Returns:

The constrained operation response.

Raises:

TypeError – If the result is not a supported response value.

Return type:

httk.serve.http.openapi.app.OpenAPIResponse

httk.serve.http.openapi.normalize_parameter_name(name)[source]

Normalize an OpenAPI wire parameter name to a Python identifier form.

Hyphens become underscores, camelCase and ACRONYMCase boundaries are split, the result is lowercased, repeated underscores collapse, and leading and trailing underscores are stripped. The returned string is not guaranteed to be a valid identifier; a wire name that does not normalize to one (for example filter[name]) is not auto-bindable and requires an explicit alias.

Parameters:

name (str) – OpenAPI wire parameter name.

Returns:

Normalized handler-parameter name candidate.

Return type:

str

httk.serve.http.openapi.operation(target, *, aliases=None, extras=())[source]

Declare an operation binding with optional aliases and request-scope extras.

Parameters:
Returns:

The declared operation binding.

Return type:

OperationBinding

class httk.serve.http.openapi.OpenAPIContract[source]

Bundle a parsed OpenAPI contract with its offline JSON Schema registry.

Parameters:
  • operations – Supported operations in document order.

  • schemas – Offline schema registry for external body references.

operations: tuple[httk.serve.http.openapi.app.OpenAPIOperation, Ellipsis]
schemas: httk.serve.http.openapi.schemas.OpenAPISchemaRegistry
classmethod from_package(package, *, contract=('schemas', 'openapi.yaml'), schemas=('schemas',), schema_transform=None)[source]

Load and parse a packaged OpenAPI contract and its bundled schemas.

Results are cached by the exact package, contract, schemas, and schema_transform arguments, so repeated calls with the same arguments do not re-parse or re-validate the packaged data.

Parameters:
  • package (str) – Importable package that ships the contract as package data.

  • contract (collections.abc.Sequence[str]) – Path segments below the package to the OpenAPI document.

  • schemas (collections.abc.Sequence[str]) – Path segments below the package to the schema root.

  • schema_transform (collections.abc.Callable[[dict[str, Any]], dict[str, Any]] | None) – Optional per-document transform applied to each bundled JSON Schema document before it is registered. It is not applied to the OpenAPI document itself. Must be a stable module-level function: it is part of the cache key by identity, so a lambda or closure never hits the cache and instead retains a fully parsed contract for its own lifetime.

Returns:

The parsed contract and its offline schema registry.

Raises:
Return type:

Self

document()[source]

Return an independent deep copy of the parsed OpenAPI document.

Returns:

Caller-owned copy of the OpenAPI document mapping.

Return type:

dict[str, Any]

operation(operation_id)[source]

Return the operation registered under an operation id.

Parameters:

operation_id (str) – Operation identifier to look up.

Returns:

The matching operation.

Raises:

httk.serve.http.openapi.OpenAPIContractError – If no operation has that id.

Return type:

httk.serve.http.openapi.app.OpenAPIOperation

validate(schema_id, document)[source]

Validate a JSON-compatible value against a bundled schema.

Parameters:
  • schema_id (str) – Schema $id.

  • document (Any) – JSON-compatible value to validate.

Raises:

httk.serve.http.openapi.OpenAPISchemaError – If the schema is unavailable or validation fails.

httk.serve.http.openapi.load_packaged_contract(package, *path)[source]

Load an OpenAPI contract from package data without network access.

The resource is read as UTF-8 and parsed according to its suffix: .yaml and .yml through yaml.safe_load, .json through json.loads(). Both formats yield the same mapping shape that httk.serve.http.openapi.create_openapi_app() consumes.

Parameters:
  • package (str) – Importable package that ships the contract as package data.

  • *path (str) – Path segments joined below the package to reach the resource.

Returns:

Parsed contract mapping.

Raises:
  • ValueError – If the resource suffix is not a supported contract format.

  • RuntimeError – If the parsed contract is not a JSON object.

Return type:

dict[str, Any]

httk.serve.http.openapi.packaged_schema_documents(package, *path)[source]

Load every bundled JSON Schema document below a package resource.

The resource tree is walked in stable sorted order; every *.json file is parsed, and those that decode to a mapping carrying a $schema key are returned unchanged.

Parameters:
  • package (str) – Importable package that ships the schema documents.

  • *path (str) – Path segments joined below the package to reach the schema root.

Returns:

Parsed JSON Schema documents in stable order.

Return type:

tuple[dict[str, Any], Ellipsis]

httk.serve.http.openapi.packaged_schema_registry(package, *path)[source]

Build an offline schema registry from bundled JSON Schema documents.

Parameters:
  • package (str) – Importable package that ships the schema documents.

  • *path (str) – Path segments joined below the package to reach the schema root.

Returns:

Registry over the bundled documents.

Raises:

httk.serve.http.openapi.OpenAPISchemaError – If any document is invalid.

Return type:

httk.serve.http.openapi.schemas.OpenAPISchemaRegistry

exception httk.serve.http.openapi.OpenAPISchemaError[source]

Bases: ValueError

Report an unavailable or invalid JSON Schema document.

class httk.serve.http.openapi.OpenAPISchemaRegistry(documents)[source]

Validate caller-supplied JSON Schema documents without network retrieval.

The registry deep-copies supplied documents, so later caller mutations do not alter validation or offline reference resolution.

Parameters:

documents (collections.abc.Iterable[collections.abc.Mapping[str, Any]]) – JSON Schema documents, each with a non-empty $id.

lookup(identifier)[source]

Return a schema document by its canonical identifier.

Parameters:

identifier (str) – Schema $id.

Returns:

Independent copy of the registered schema mapping.

Raises:

OpenAPISchemaError – If no supplied schema has that identifier.

Return type:

collections.abc.Mapping[str, Any]

validate(identifier, value)[source]

Validate a JSON-compatible value against an offline schema.

Parameters:
  • identifier (str) – Schema $id.

  • value (Any) – JSON-compatible value to validate.

Raises:

OpenAPISchemaError – If the schema is unavailable or validation fails.

property identifiers: tuple[str, Ellipsis]

Return supplied schema identifiers in caller order.