httk.serve.http.openapi¶
A constrained, offline OpenAPI 3.1 adapter for Starlette.
Submodules¶
Attributes¶
A zero-argument coroutine callback run once, after the response has been sent. |
|
The httk-serve serving application type (a Starlette app; branded so consumers need not import Starlette). |
|
Exceptions¶
Report an unsupported or internally inconsistent OpenAPI contract. |
|
Report adapter-generated request parsing or validation failure. |
|
Report an unavailable or invalid JSON Schema document. |
Classes¶
Describe one supported OpenAPI operation. |
|
Describe one supported string OpenAPI parameter. |
|
Normalized values passed to an OpenAPI operation handler. |
|
A handler response constrained by the matched OpenAPI operation. |
|
A validated binding of one operation to its resolved handler callable. |
|
Describe where one handler parameter's value is resolved from per request. |
|
Declare how one operation's declared inputs bind to a handler callable. |
|
Carry per-request values between a request scope and one operation handler. |
|
Bundle a parsed OpenAPI contract with its offline JSON Schema registry. |
|
Validate caller-supplied JSON Schema documents without network retrieval. |
Functions¶
|
Create a Starlette app from a constrained OpenAPI 3.1 contract. |
|
Parse the supported OpenAPI 3.1 path subset. |
|
Validate and bind one operation's declared inputs to its handler by name. |
|
Convert a handler return value into a constrained operation response. |
|
Normalize an OpenAPI wire parameter name to a Python identifier form. |
|
Declare an operation binding with optional aliases and request-scope extras. |
|
Load an OpenAPI contract from package data without network access. |
|
Load every bundled JSON Schema document below a package resource. |
|
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
Starletteclass, so useStarletteitself forisinstance/subclass checks.
- type httk.serve.http.openapi.ExceptionHandler = Callable[[Exception, 'OpenAPIRequest'], 'OpenAPIResponse | Awaitable[OpenAPIResponse]'][source]¶
- exception httk.serve.http.openapi.OpenAPIContractError[source]¶
Bases:
ValueErrorReport 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
Nonewhen the operation declares zero or more than one.
- parameters: tuple[OpenAPIParameter, Ellipsis]¶
- 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 forsuccess_status, or an empty tuple when there is no single declared success status.- Return type:
- class httk.serve.http.openapi.OpenAPIParameter[source]¶
Describe one supported string OpenAPI parameter.
- Parameters:
name – Parameter name as declared by OpenAPI.
location –
path,query, orheader.required – Whether the parameter must be sent.
enum – Optional exact set of accepted string values.
- 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
Nonefor 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¶
- exception httk.serve.http.openapi.OpenAPIRequestError(operation, detail, request)[source]¶
Bases:
ValueErrorReport 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
Noneto 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.
- body: Any = 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.
contractaccepts either anOpenAPIContract, which already bundles its offline schema registry, or a plain OpenAPI document mapping paired with a separateschemasregistry.Each
operationsentry is a bare handler callable or anOperationBinding. 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; seeoperation().- 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;
Noneuses each entry callable directly.schemas (httk.serve.http.openapi.schemas.OpenAPISchemaRegistry | None) – Offline JSON Schema registry for external body references. Required and used when
contractis a plain mapping; must not be supplied whencontractis anOpenAPIContract.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
OperationContextextras 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
contractandschemasdisagree about which schema registry to use.- Return type:
- 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:
operation (httk.serve.http.openapi.app.OpenAPIOperation) – The operation this binding serves.
target (collections.abc.Callable[Ellipsis, Any]) – Resolved handler callable to invoke.
sources (collections.abc.Sequence[BoundParameter]) – Per-request sources for the handler’s bound parameters.
- 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, orextra.key – Lookup key within the source; the wire parameter name (lowercased for headers) for parameter sources, the scope name for
extra, and unused forbodyandrequest.
- 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
implementationwhen the application is created.aliases – Wire parameter name to handler parameter name overrides. The reserved wire name
bodyremaps the request body.extras – Names of request-scope values this operation consumes.
- target: collections.abc.Callable[Ellipsis, Any]¶
- aliases: collections.abc.Mapping[str, str]¶
- class httk.serve.http.openapi.OperationContext[source]¶
Carry per-request values between a request scope and one operation handler.
The scope populates
extrasbefore the handler runs; the framework passes each extra the operation declares to the handler by name. After the handler returns, the scope may setmedia_type,headers, andafter_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.
- 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:
operation (httk.serve.http.openapi.app.OpenAPIOperation) – The declared operation to bind.
entry (collections.abc.Callable[Ellipsis, Any] | OperationBinding) – A bare handler callable, or an
OperationBinding.implementation (object | None) – Object whose methods resolve class-defined function entries;
Noneuses each entry callable directly.scope_names (collections.abc.Collection[str]) – Request-scope value names available to
extras.
- Returns:
The validated per-request binding.
- Raises:
OpenAPIContractError – If the handler cannot satisfy the operation’s declared inputs by name.
- Return type:
- 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.
Nonebecomes the bodyless success response, a mapping or list becomes a response body, and anOpenAPIResponseis used as is.
- httk.serve.http.openapi.normalize_parameter_name(name)[source]¶
Normalize an OpenAPI wire parameter name to a Python identifier form.
Hyphens become underscores,
camelCaseandACRONYMCaseboundaries 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 examplefilter[name]) is not auto-bindable and requires an explicit alias.
- httk.serve.http.openapi.operation(target, *, aliases=None, extras=())[source]¶
Declare an operation binding with optional aliases and request-scope extras.
- Parameters:
target (collections.abc.Callable[Ellipsis, Any]) – Callable implementing the operation.
aliases (collections.abc.Mapping[str, str] | None) – Wire parameter name to handler parameter name overrides.
extras (collections.abc.Sequence[str]) – Names of request-scope values this operation consumes.
- Returns:
The declared operation binding.
- Return type:
- 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]¶
- 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, andschema_transformarguments, 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:
httk.serve.http.openapi.OpenAPIContractError – If the OpenAPI document uses an unsupported construct.
httk.serve.http.openapi.OpenAPISchemaError – If any bundled schema document is invalid.
- Return type:
Self
- 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:
- 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:
.yamland.ymlthroughyaml.safe_load,.jsonthroughjson.loads(). Both formats yield the same mapping shape thathttk.serve.http.openapi.create_openapi_app()consumes.- Parameters:
- 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:
- 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
*.jsonfile is parsed, and those that decode to a mapping carrying a$schemakey are returned unchanged.
- httk.serve.http.openapi.packaged_schema_registry(package, *path)[source]¶
Build an offline schema registry from bundled JSON Schema documents.
- Parameters:
- Returns:
Registry over the bundled documents.
- Raises:
httk.serve.http.openapi.OpenAPISchemaError – If any document is invalid.
- Return type:
- exception httk.serve.http.openapi.OpenAPISchemaError[source]¶
Bases:
ValueErrorReport 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.