Skip to content

OpenAPI & Encoding

Schema generation and the JSON encoding layer.

use_json_backend

use_json_backend(choice: JSONBackend | str) -> None

Select the JSON backend for this process. Call it once, at startup.

Every module reaches JSON by looking these names up here, so one call moves all of them together - response bodies, jsonify, signed cookies and tokens, cache keys, config files and the MCP transports.

Process-wide rather than per-app on purpose: one interpreter has one backend, and an app-scoped setting would let a second app silently redefine the first's wire format. Call it before anything is encoded; switching later leaves cache entries keyed by the previous backend, which then miss rather than fail.

JSONBackend

Bases: str, Enum

The JSON implementations use_json_backend accepts.

Each member's value is the name VELOCE_JSON_BACKEND and backend use, so STDLIB reads "json" while the rest match their member name.

jsonable_encoder

jsonable_encoder(obj: Any, include: set[str] | None = None, exclude: set[str] | None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, custom_encoder: dict[type[Any], Callable[[Any], Any]] | None = None, *, _seen: set[int] | None = None) -> Any

Convert complex objects to JSON-serializable types.

Handles Pydantic models, dataclasses, datetime, Decimal, UUID, Enum, Path, sets, frozensets, and nested structures.

Every filter applies at every depth, not only to the top-level object: exclude={"password"} strips that key wherever it appears, and exclude_unset / exclude_defaults reach a model nested in a dict or list.

include is the same rule read the other way - a whitelist of key names applied at every depth, not a selection of top-level fields. A nesting key must be listed too, or the branch holding the value is dropped: include={"a"} gives {"a": {}} where include={"a", "b"} keeps a's b. Pydantic's model_dump(include=...) selects at one level instead.

Raises ValueError on a self-referential object graph rather than recursing until the stack overflows. The per-call _seen set is internal.

custom_encoder is an optional {type: fn} mapping consulted before every built-in rule at every depth - exact type(obj) first, else the first isinstance match in insertion order - so it can override container and model handling too. register_encoder types are consulted later and cover subclasses through an MRO walk.

Usage::

data = jsonable_encoder(my_pydantic_model, exclude={"password"})

register_encoder

register_encoder(type_: type[Any], encoder: Callable[[Any], Any]) -> None

Register a process-level JSON encoder for type_ and its subclasses.

encoder receives one instance and must return a JSON-able value. It is consulted after the exact-type fast paths, resolved via an MRO walk so subclasses of type_ are covered, and overrides any built-in handler for the same type.

Usage::

register_encoder(MyId, lambda v: v.hex)

unregister_encoder

unregister_encoder(type_: type[Any]) -> None

Remove a previously registered encoder for type_.

No-op if type_ was never registered.

JSONProvider

Base class for JSON serialisation providers.

Subclass to plug in an alternative serialiser, then point the app at it via app.json (an instance) or app.json_provider_class (a class, instantiated lazily on first access).

Usage::

class MyJSONProvider(JSONProvider):
    def dumps(self, obj, **kwargs):
        return my_lib.dumps(obj).encode()

    def loads(self, data):
        return my_lib.loads(data)

app.json_provider_class = MyJSONProvider

dumps

dumps(obj: Any, **kwargs: Any) -> bytes

Serialise obj to JSON bytes. Subclasses override.

bytes, not str, so a caller can write straight to a response body. The kwargs catch-all is provider-specific.

loads

loads(data: bytes | str) -> Any

Parse JSON data into Python objects.

response

response(value: Any, **kwargs: Any) -> Response

Build a Response carrying value as JSON.

DefaultJSONProvider

Bases: JSONProvider

Provider over the configured JSON backend — Veloce's default.

Honours the JSON_SORT_KEYS / JSONIFY_PRETTYPRINT_REGULAR config flags, so neither needs a subclass.

response

response(value: Any, **kwargs: Any) -> Response

Build a Response carrying value as JSON.

config_orjson_options

config_orjson_options(cfg: Any) -> int

Build the JSON option bitmask from an app config mapping.

Reads JSON_SORT_KEYS and JSONIFY_PRETTYPRINT_REGULAR; 0 when cfg is None.

get_openapi_schema

get_openapi_schema(app: Any) -> dict[str, Any]

Generate OpenAPI 3.1 schema from the app's registered routes.

setup_openapi_routes

setup_openapi_routes(app: Any, openapi_url: str = '/openapi.json', docs_url: str | None = '/docs', redoc_url: str | None = '/redoc') -> None

Register OpenAPI schema and documentation routes.

docs_url / redoc_url of None disable the Swagger UI / ReDoc UI respectively - the JSON schema route is still registered, so tooling can consume the schema without a public interactive explorer.