GitHub

API reference for schema.

How endpoint schemas meet HTTP (Effect's HttpApiSchema): the status of a response, its encoding (JSON, form, text, bytes, multipart), empty responses, streams, upgrades and response headers.

Annotations are read from a schema's node: http_api_status (the status), http_api_encoding (an Encoding) and http_api_with_headers (encode_to_with_headers).

Values

AttributeTypeDescription
VoidBottom[None]

No body (Effect's Schema.Void): None, sent as an empty body.

NoContentBottom[None]
CreatedBottom[None]
AcceptedBottom[None]
RESERVED_STREAM_FAILURE_EVENTLiteral['effect/http-api/stream/failure'] = 'effect/http-api/stream/failure'

Types

TypeDefinitionDescription
ResponseEncodingTagtype ResponseEncodingTag = Literal['Json', 'FormUrlEncoded', 'Uint8Array', 'Text']
PayloadEncodingtype PayloadEncoding = ResponseEncoding | MultipartEncoding
StreamSseModetype StreamSseMode = Literal['events', 'data']
StreamSchematype StreamSchema = StreamSseSchema[Any, Any] | StreamUint8ArraySchema | StreamNdjsonSchema[Any]

Classes

Functions

encoding_of

encoding_of(node) -> PayloadEncoding | None

The http_api_encoding annotation of node.

ParameterTypeDescription
nodeast.AST

Returns PayloadEncoding | None

def encoding_of(node: ast.AST) -> PayloadEncoding | None:
    """The ``http_api_encoding`` annotation of ``node``."""
    return cast("PayloadEncoding | None", _annotation(node, "http_api_encoding"))

get_payload_encoding

get_payload_encoding(node, method) -> PayloadEncoding

A payload's encoding: its annotation, else JSON for a method with a body and a query string for one without.

ParameterTypeDescription
nodeast.AST
methodHttpMethod

Returns PayloadEncoding

def get_payload_encoding(node: ast.AST, method: HttpMethod) -> PayloadEncoding:
    """A payload's encoding: its annotation, else JSON for a method with a
    body and a query string for one without."""
    encoding = encoding_of(node)
    if encoding is not None:
        return encoding
    return _JSON if has_body(method) else _FORM

get_response_encoding

get_response_encoding(node) -> ResponseEncoding

A response's encoding: its annotation, else JSON. Multipart is a ValueError.

ParameterTypeDescription
nodeast.AST

Returns ResponseEncoding

def get_response_encoding(node: ast.AST) -> ResponseEncoding:
    """A response's encoding: its annotation, else JSON. Multipart is a
    ``ValueError``."""
    encoding = encoding_of(node) or _JSON
    if isinstance(encoding, MultipartEncoding):
        raise ValueError("Multipart is not supported in response")
    return encoding

as_json

as_json(*, content_type='application/json') -> _Annotate

Encode the body as JSON (the default). Use with .pipe.

ParameterTypeDescription
content_typestr = 'application/json'

Returns _Annotate

def as_json(*, content_type: str = "application/json") -> _Annotate:
    """Encode the body as JSON (the default). Use with ``.pipe``."""
    return _encoding(ResponseEncoding("Json", content_type))

as_form_url_encoded

as_form_url_encoded(*, content_type='application/x-www-form-urlencoded') -> _Annotate

Encode the body as URL parameters. Use with .pipe.

ParameterTypeDescription
content_typestr = 'application/x-www-form-urlencoded'

Returns _Annotate

def as_form_url_encoded(*, content_type: str = "application/x-www-form-urlencoded") -> _Annotate:
    """Encode the body as URL parameters. Use with ``.pipe``."""
    return _encoding(ResponseEncoding("FormUrlEncoded", content_type))

as_text

as_text(*, content_type='text/plain') -> _Annotate

Send the encoded string as the body. Use with .pipe.

ParameterTypeDescription
content_typestr = 'text/plain'

Returns _Annotate

def as_text(*, content_type: str = "text/plain") -> _Annotate:
    """Send the encoded string as the body. Use with ``.pipe``."""
    return _encoding(ResponseEncoding("Text", content_type))

as_uint8_array

as_uint8_array(*, content_type='application/octet-stream') -> _Annotate

Send the encoded bytes as the body. Use with .pipe.

ParameterTypeDescription
content_typestr = 'application/octet-stream'

Returns _Annotate

def as_uint8_array(*, content_type: str = "application/octet-stream") -> _Annotate:
    """Send the encoded bytes as the body. Use with ``.pipe``."""
    return _encoding(ResponseEncoding("Uint8Array", content_type))

as_multipart

as_multipart[A, RD](schema, **limits) -> MultipartSchema[A, RD]

schema read from a parsed multipart/form-data body (files persisted first), within limits.

ParameterTypeDescription
schemaCodec[A, Any, RD, Any]
limitsUnpack[Limits] = {}

Returns MultipartSchema[A, RD]

def as_multipart[A, RD](
    schema: Codec[A, Any, RD, Any], /, **limits: Unpack[Limits]
) -> MultipartSchema[A, RD]:
    """``schema`` read from a parsed ``multipart/form-data`` body (files
    persisted first), within ``limits``."""
    encoding = MultipartEncoding("buffered", "multipart/form-data", limits or None)
    return MultipartSchema(schema.__codec__().annotate(http_api_encoding=encoding).ast)

as_multipart_stream

as_multipart_stream(schema, **limits) -> MultipartStreamSchema

A multipart/form-data body as a stream of parts, within limits; schema documents the form (its files binary).

ParameterTypeDescription
schemaTop
limitsUnpack[Limits] = {}

Returns MultipartStreamSchema

def as_multipart_stream(schema: Top, /, **limits: Unpack[Limits]) -> MultipartStreamSchema:
    """A ``multipart/form-data`` body as a stream of parts, within
    ``limits``; ``schema`` documents the form (its files binary)."""
    encoding = MultipartEncoding("stream", "multipart/form-data", limits or None)
    documented = schema.__codec__().ast
    annotated = _STREAM.annotate(http_api_encoding=encoding, http_api_documented=documented)
    return MultipartStreamSchema(annotated.ast)

documented_node

documented_node(node) -> ast.AST

The schema documenting node's body: the form of a multipart stream, otherwise node.

ParameterTypeDescription
nodeast.AST

Returns ast.AST

def documented_node(node: ast.AST) -> ast.AST:
    """The schema documenting ``node``'s body: the form of a multipart
    stream, otherwise ``node``."""
    documented = (node.annotations or {}).get("http_api_documented")
    return documented if isinstance(documented, ast.AST) else node

is_multipart_stream

is_multipart_stream(schema) -> bool
ParameterTypeDescription
schemaTop

Returns bool

def is_multipart_stream(schema: Top) -> bool:
    encoding = encoding_of(schema.__codec__().ast)
    return isinstance(encoding, MultipartEncoding) and encoding.mode == "stream"

resolve_status

resolve_status(node) -> int | None

The http_api_status of node or of the key holding it.

ParameterTypeDescription
nodeast.AST

Returns int | None

def resolve_status(node: ast.AST) -> int | None:
    """The ``http_api_status`` of ``node`` or of the key holding it."""
    annotations = _status_annotations(node)
    if annotations is not None:
        return cast("int | None", annotations["http_api_status"])
    return cast("int | None", (node.key_annotations or {}).get("http_api_status"))

status

status(code) -> _Annotate

Respond with code (a number or a name like "Created") when the schema encodes the value. Use with .pipe.

ParameterTypeDescription
codeint | StatusLiteral

Returns _Annotate

def status(code: int | StatusLiteral) -> _Annotate:
    """Respond with ``code`` (a number or a name like ``"Created"``) when
    the schema encodes the value. Use with ``.pipe``."""
    number = http_status.from_literal(code) if isinstance(code, str) else code
    return _StatusAnnotate(number)

get_status_success

get_status_success(node) -> int
ParameterTypeDescription
nodeast.AST

Returns int

def get_status_success(node: ast.AST) -> int:
    return resolve_status(node) or 200

get_status_error

get_status_error(node) -> int
ParameterTypeDescription
nodeast.AST

Returns int

def get_status_error(node: ast.AST) -> int:
    return resolve_status(node) or 500

is_with_headers

is_with_headers(value) -> TypeIs[WithHeadersSchema[Any, Any]]
ParameterTypeDescription
valueobject

Returns TypeIs[WithHeadersSchema[Any, Any]]

def is_with_headers(value: object) -> TypeIs[WithHeadersSchema[Any, Any]]:
    return isinstance(value, WithHeadersSchema)

is_upgrade

is_upgrade(value) -> TypeIs[UpgradeSchema[Any]]
ParameterTypeDescription
valueobject

Returns TypeIs[UpgradeSchema[Any]]

def is_upgrade(value: object) -> TypeIs[UpgradeSchema[Any]]:
    return isinstance(value, UpgradeSchema)

body_of

body_of(schema) -> Top

The body schema of a WithHeaders response, else schema.

ParameterTypeDescription
schemaTop

Returns Top

def body_of(schema: Top) -> Top:
    """The body schema of a ``WithHeaders`` response, else ``schema``."""
    if is_with_headers(schema):
        return schema.schema
    return schema

get_status_success_schema

get_status_success_schema(schema) -> int

The status a success schema responds with (default 200).

ParameterTypeDescription
schemaTop

Returns int

def get_status_success_schema(schema: Top) -> int:
    """The status a success schema responds with (default 200)."""
    if is_with_headers(schema):
        return resolve_status(schema.ast) or get_status_success(body_of(schema).__codec__().ast)
    return get_status_success(schema.__codec__().ast)

get_status_error_schema

get_status_error_schema(schema) -> int

The status an error schema responds with (default 500).

ParameterTypeDescription
schemaTop

Returns int

def get_status_error_schema(schema: Top) -> int:
    """The status an error schema responds with (default 500)."""
    if is_with_headers(schema):
        return resolve_status(schema.ast) or get_status_error(body_of(schema).__codec__().ast)
    return get_status_error(schema.__codec__().ast)

get_response_encoding_schema

get_response_encoding_schema(schema) -> ResponseEncoding
ParameterTypeDescription
schemaTop

Returns ResponseEncoding

def get_response_encoding_schema(schema: Top) -> ResponseEncoding:
    if is_with_headers(schema) and encoding_of(schema.ast) is None:
        return get_response_encoding(body_of(schema).__codec__().ast)
    return get_response_encoding(schema.__codec__().ast)

is_no_content

is_no_content(node) -> bool

node is (or is encoded to) Void: the response has no body.

ParameterTypeDescription
nodeast.AST

Returns bool

def is_no_content(node: ast.AST) -> bool:
    """``node`` is (or is encoded to) ``Void``: the response has no body."""
    if _is_void(node) or _is_void(ast.to_encoded(node)):
        return True
    return node.encoding is not None and _is_void(node.encoding[0].to)

Empty

Empty(code) -> Bottom[None]

No body, with status code.

ParameterTypeDescription
codeint

Returns Bottom[None]

def Empty(code: int) -> Bottom[None]:
    """No body, with status ``code``."""
    return status(code)(Void)

as_no_content

as_no_content[A](schema, /, *, decode) -> Bottom[A, None]

schema's values sent as an empty body; a client makes the value with decode().

ParameterTypeDescription
schemaCodec[A, Any, Any, Any]
decodeCallable[[], A]

Returns Bottom[A, None]

def as_no_content[A](
    schema: Codec[A, Any, Any, Any], /, *, decode: Callable[[], A]
) -> Bottom[A, None]:
    """``schema``'s values sent as an empty body; a client makes the value
    with ``decode()``."""
    transformation: T.Transformation[A, None] = T.transform(
        decode=lambda _: decode(), encode=lambda _: None
    )
    return Void.pipe(decode_to(to_type(schema), transformation))

as_problem

as_problem(*, title, type=BLANK_TYPE, decode=None) -> _AsProblem

An error class sent as an RFC 9457 problem (Effect's asProblem): an application/problem+json body with type, title and the class's status. A client decodes a body of the same type with decode() (default: the class called without arguments); another type is rejected. Use with .pipe.

ParameterTypeDescription
titlestr
typestr = BLANK_TYPE
decodeCallable[[], Any] | None = None

Returns _AsProblem

def as_problem(
    *, title: str, type: str = BLANK_TYPE, decode: Callable[[], Any] | None = None
) -> _AsProblem:
    """An error class sent as an RFC 9457 problem (Effect's ``asProblem``):
    an ``application/problem+json`` body with ``type``, ``title`` and the
    class's status. A client decodes a body of the same ``type`` with
    ``decode()`` (default: the class called without arguments); another
    ``type`` is rejected. Use with ``.pipe``."""
    return _AsProblem(type, title, decode)

StreamSse

StreamSse[A, E = Never](*, events: Codec[A, Mapping[str, object], Any, Any], error: Codec[E, Any, Any, Any] | None = None, content_type: str | Sequence[str] = 'text/event-stream') -> StreamSseSchema[A, E]
StreamSse[A, E = Never](*, data: Codec[A, Any, Any, Any], error: Codec[E, Any, Any, Any] | None = None, content_type: str | Sequence[str] = 'text/event-stream') -> StreamSseSchema[A, E]

Server-sent events: each decoded by events from its fields (event, data, id), or message events whose JSON data data decodes (the stream is of the data values). error encodes the stream's failure, sent as a reserved event. data is written with its JSON codec (to_codec_json).

ParameterTypeDescription
events= None
data= None
error= None
content_type= 'text/event-stream'
@overload
def StreamSse[A, E = Never](
    *,
    events: Codec[A, Mapping[str, object], Any, Any],
    error: Codec[E, Any, Any, Any] | None = None,
    content_type: str | Sequence[str] = "text/event-stream",
) -> StreamSseSchema[A, E]: ...
@overload
def StreamSse[A, E = Never](
    *,
    data: Codec[A, Any, Any, Any],
    error: Codec[E, Any, Any, Any] | None = None,
    content_type: str | Sequence[str] = "text/event-stream",
) -> StreamSseSchema[A, E]: ...
def StreamSse(
    *,
    events: Codec[Any, Mapping[str, object], Any, Any] | None = None,
    data: Codec[Any, Any, Any, Any] | None = None,
    error: Codec[Any, Any, Any, Any] | None = None,
    content_type: str | Sequence[str] = "text/event-stream",
) -> StreamSseSchema[Any, Any]:
    """Server-sent events: each decoded by ``events`` from its fields
    (``event``, ``data``, ``id``), or ``message`` events whose JSON data
    ``data`` decodes (the stream is of the data values). ``error`` encodes
    the stream's failure, sent as a reserved event. ``data`` is written
    with its JSON codec (``to_codec_json``)."""
    if data is not None:
        events = Struct(_SseDataFields, data=from_json_string(to_codec_json(data)))
    elif events is None:
        raise TypeError("StreamSse needs events or data")
    return StreamSseSchema(
        _STREAM.ast,
        sse_mode="data" if data is not None else "events",
        **_content_types(content_type),
        events=events,
        error=error if error is not None else _NEVER,
    )

StreamUint8Array

StreamUint8Array(*, content_type='application/octet-stream', max_bytes=None) -> StreamUint8ArraySchema

A byte stream body; as a payload, at most max_bytes. A list of content types sends the stream under several media types: the first is the response's, and a payload is taken under any of them.

ParameterTypeDescription
content_typestr | Sequence[str] = 'application/octet-stream'
max_bytesbyte_size.Input | None = None

Returns StreamUint8ArraySchema

def StreamUint8Array(
    *,
    content_type: str | Sequence[str] = "application/octet-stream",
    max_bytes: byte_size.Input | None = None,
) -> StreamUint8ArraySchema:
    """A byte stream body; as a payload, at most ``max_bytes``. A list of
    content types sends the stream under several media types: the first is
    the response's, and a payload is taken under any of them."""
    return StreamUint8ArraySchema(
        _STREAM.ast, **_content_types(content_type), max_bytes=_sizes(max_bytes)
    )

StreamNdjson

StreamNdjson[A](schema, *, content_type='application/x-ndjson', max_bytes=None, max_element_bytes=None) -> StreamNdjsonSchema[A]

Newline-delimited JSON of schema values; a line is at most max_element_bytes (1 MiB). A list of content types takes aliases such as application/jsonl; the first is the default.

ParameterTypeDescription
schemaCodec[A, Any, Any, Any]
content_typestr | Sequence[str] = 'application/x-ndjson'
max_bytesbyte_size.Input | None = None
max_element_bytesbyte_size.Input | None = None

Returns StreamNdjsonSchema[A]

def StreamNdjson[A](
    schema: Codec[A, Any, Any, Any],
    *,
    content_type: str | Sequence[str] = "application/x-ndjson",
    max_bytes: byte_size.Input | None = None,
    max_element_bytes: byte_size.Input | None = None,
) -> StreamNdjsonSchema[A]:
    """Newline-delimited JSON of ``schema`` values; a line is at most
    ``max_element_bytes`` (1 MiB). A list of content types takes aliases
    such as ``application/jsonl``; the first is the default."""
    return StreamNdjsonSchema(
        _STREAM.ast,
        **_content_types(content_type),
        schema=schema,
        max_bytes=_sizes(max_bytes),
        max_element_bytes=_sizes(max_element_bytes) or _DEFAULT_MAX_ELEMENT_BYTES,
    )

is_stream_payload

is_stream_payload(value) -> TypeIs[StreamUint8ArraySchema | StreamNdjsonSchema[Any]]

A schema of a streamed payload.

ParameterTypeDescription
valueobject

Returns TypeIs[StreamUint8ArraySchema | StreamNdjsonSchema[Any]]

def is_stream_payload(
    value: object,
) -> TypeIs[StreamUint8ArraySchema | StreamNdjsonSchema[Any]]:
    """A schema of a streamed payload."""
    return isinstance(value, (StreamUint8ArraySchema, StreamNdjsonSchema))

is_stream_schema

is_stream_schema(value) -> TypeIs[StreamSchema]
ParameterTypeDescription
valueobject

Returns TypeIs[StreamSchema]

def is_stream_schema(value: object) -> TypeIs[StreamSchema]:
    return isinstance(value, (StreamSseSchema, StreamUint8ArraySchema, StreamNdjsonSchema))

Upgrade

Upgrade(protocol: str) -> UpgradeSchema[Headers]
Upgrade[H](protocol: str, *, headers: Codec[H, Any, Never, Never]) -> UpgradeSchema[H]

A protocol upgrade (Effect's Upgrade); WebSocket is not one (ValueError: serve it with a router route).

ParameterTypeDescription
protocol
headers= None
@overload
def Upgrade(protocol: str) -> UpgradeSchema[Headers]: ...
@overload
def Upgrade[H](protocol: str, *, headers: Codec[H, Any, Never, Never]) -> UpgradeSchema[H]: ...
def Upgrade(
    protocol: str, *, headers: Codec[Any, Any, Never, Never] | None = None
) -> UpgradeSchema[Any]:
    """A protocol upgrade (Effect's ``Upgrade``); WebSocket is not one
    (``ValueError``: serve it with a router route)."""
    if protocol.lower() == "websocket":
        raise ValueError("Upgrade does not support WebSocket")
    return UpgradeSchema(_UPGRADE.ast, protocol=protocol, headers=headers)

with_headers

with_headers[A, H](body, headers) -> WithHeadersValue[A, H]
ParameterTypeDescription
bodyA
headersH

Returns WithHeadersValue[A, H]

def with_headers[A, H](body: A, headers: H) -> WithHeadersValue[A, H]:
    return WithHeadersValue(body, headers)

WithHeaders

WithHeaders[A, H](schema, headers) -> WithHeadersSchema[A, H]

schema's response sent with headers (Effect's WithHeaders). Nesting and upgrades are ValueErrors.

ParameterTypeDescription
schemaCodec[A, Any, Any, Any]
headersCodec[H, Any, Any, Any]

Returns WithHeadersSchema[A, H]

def WithHeaders[A, H](
    schema: Codec[A, Any, Any, Any], headers: Codec[H, Any, Any, Any]
) -> WithHeadersSchema[A, H]:
    """``schema``'s response sent with ``headers`` (Effect's
    ``WithHeaders``). Nesting and upgrades are ``ValueError``s."""
    if is_with_headers(schema):
        raise ValueError("WithHeaders schemas cannot be nested")
    if is_upgrade(schema):
        raise ValueError("WithHeaders cannot wrap an upgrade")
    return WithHeadersSchema(_WITH_HEADERS.ast, schema=schema, headers=headers)

rebuild_with_headers

rebuild_with_headers(self, schema, headers) -> WithHeadersSchema[Any, Any]
ParameterTypeDescription
selfWithHeadersSchema[Any, Any]
schemaTop
headersTop

Returns WithHeadersSchema[Any, Any]

def rebuild_with_headers(
    self: WithHeadersSchema[Any, Any], schema: Top, headers: Top
) -> WithHeadersSchema[Any, Any]:
    return replace(self, schema=schema, headers=headers)

get_with_headers_annotation

get_with_headers_annotation(node) -> WithHeadersAnnotation | None
ParameterTypeDescription
nodeast.AST

Returns WithHeadersAnnotation | None

def get_with_headers_annotation(node: ast.AST) -> WithHeadersAnnotation | None:
    return cast("WithHeadersAnnotation | None", _annotation(node, "http_api_with_headers"))

encode_to_with_headers

encode_to_with_headers[A, B, H](schema, /, *, body, headers, decode, encode) -> Bottom[A, Mapping[str, object]]

schema's values sent as body with headers: encode splits a value into both, decode joins them (Effect's encodeToWithHeaders). The status and encoding are body's.

ParameterTypeDescription
schemaCodec[A, Any, Any, Any]
bodyCodec[B, Any, Any, Any]
headersCodec[H, Any, Any, Any]
decodeCallable[[_WithHeadersPair[B, H]], A]
encodeCallable[[A], _WithHeadersPair[B, H]]

Returns Bottom[A, Mapping[str, object]]

def encode_to_with_headers[A, B, H](
    schema: Codec[A, Any, Any, Any],
    /,
    *,
    body: Codec[B, Any, Any, Any],
    headers: Codec[H, Any, Any, Any],
    decode: Callable[[_WithHeadersPair[B, H]], A],
    encode: Callable[[A], _WithHeadersPair[B, H]],
) -> Bottom[A, Mapping[str, object]]:
    """``schema``'s values sent as ``body`` with ``headers``: ``encode``
    splits a value into both, ``decode`` joins them (Effect's
    ``encodeToWithHeaders``). The status and encoding are ``body``'s."""
    if is_upgrade(body):
        raise ValueError("encodeToWithHeaders cannot wrap an upgrade")
    body_node = body.__codec__().ast
    pair = Bottom[Any, Mapping[str, object]](
        ast.Objects(
            (
                ast.PropertySignature("body", body_node),
                ast.PropertySignature("headers", headers.__codec__().ast),
            )
        )
    )
    transformation: T.Transformation[A, Any] = T.transform(decode=decode, encode=encode)
    annotation = WithHeadersAnnotation(
        body, headers, body, headers, cast("Any", decode), cast("Any", encode)
    )
    return pair.pipe(decode_to(to_type(schema), transformation)).annotate(
        http_api_with_headers=annotation,
        http_api_status=resolve_status(body_node),
        http_api_encoding=encoding_of(body_node),
    )