GitHub

API reference for body.

Request bodies (Effect's HttpBody).

A body is one of Empty, Raw (anything the client sends as is), Bytes (bytes with a content type and length), FormData (a multipart form) or Stream (a byte stream, sent as it is pulled)::

body.text("hello")                    # text/plain
body.json_unsafe({"id": 1})           # application/json
body.stream(chunks, "text/csv")       # streamed

Re-exports

Values

AttributeTypeDescription
EMPTYEmpty

Types

TypeDefinitionDescription
FileContenttype FileContent = bytes | Callable[[], Stream_[bytes, object]]

A form file's bytes, or a function opening a stream of them each time the form is sent (a web File's stream()): read on demand, as the connection takes them.

FormDataValuetype FormDataValue = str | File
HttpBodytype HttpBody = Empty | Raw | Bytes | FormData | Stream
FormDataCoercibletype FormDataCoercible = str | int | float | bool | File | None
FormDataInputtype FormDataInput = Mapping[str, FormDataCoercible | Sequence[FormDataCoercible]]

Classes

Functions

raw

raw(body, *, content_type=None, content_length=None) -> Raw
ParameterTypeDescription
bodyobject
content_typestr | None = None
content_lengthint | None = None

Returns Raw

def raw(body: object, *, content_type: str | None = None, content_length: int | None = None) -> Raw:
    return Raw(body, content_type, content_length)

bytes_

bytes_(body, content_type=None) -> Bytes

Bytes, application/octet-stream unless content_type says otherwise (Effect's uint8Array).

ParameterTypeDescription
bodybytes
content_typestr | None = None

Returns Bytes

def bytes_(body: bytes, content_type: str | None = None) -> Bytes:
    """Bytes, ``application/octet-stream`` unless ``content_type`` says
    otherwise (Effect's ``uint8Array``)."""
    return Bytes(body, content_type or "application/octet-stream", len(body))

text

text(body, content_type=None) -> Bytes

UTF-8 text (a lone surrogate becomes U+FFFD), text/plain by default.

ParameterTypeDescription
bodystr
content_typestr | None = None

Returns Bytes

def text(body: str, content_type: str | None = None) -> Bytes:
    """UTF-8 text (a lone surrogate becomes U+FFFD), ``text/plain`` by
    default."""
    encoded = text_encode(body)
    return Bytes(encoded, content_type or "text/plain", len(encoded), body)

json_unsafe

json_unsafe(body, content_type=None) -> Bytes

body as JSON.stringify writes it (NaN as null); raises when it has no JSON form.

ParameterTypeDescription
bodyobject
content_typestr | None = None

Returns Bytes

def json_unsafe(body: object, content_type: str | None = None) -> Bytes:
    """``body`` as ``JSON.stringify`` writes it (``NaN`` as ``null``);
    raises when it has no JSON form."""
    return text(stringify(body), content_type or "application/json")

json

json(body, content_type=None) -> Effect[Bytes, HttpBodyError]

body as JSON, failing with a JsonError when it has no JSON form.

ParameterTypeDescription
bodyobject
content_typestr | None = None

Returns Effect[Bytes, HttpBodyError]

def json(body: object, content_type: str | None = None) -> Effect[Bytes, HttpBodyError]:
    """``body`` as JSON, failing with a ``JsonError`` when it has no JSON
    form."""

    def encode() -> Effect[Bytes, HttpBodyError]:
        try:
            return succeed(json_unsafe(body, content_type))
        except STRINGIFY_ERRORS as cause:
            return fail(HttpBodyError(JsonError(), cause))

    return suspend(encode)

json_schema

json_schema[T, RE](schema, **options) -> Callable[[T, str | None], Effect[Bytes, HttpBodyError, RE]]

An encoder of schema's values to JSON bodies; a value the schema rejects fails with a SchemaError reason.

ParameterTypeDescription
schemaCodec[T, object, object, RE]
optionsUnpack[ParseOptions] = {}

Returns Callable[[T, str | None], Effect[Bytes, HttpBodyError, RE]]

def json_schema[T, RE](
    schema: Codec[T, object, object, RE], **options: Unpack[ParseOptions]
) -> Callable[[T, str | None], Effect[Bytes, HttpBodyError, RE]]:
    """An encoder of ``schema``'s values to JSON bodies; a value the schema
    rejects fails with a ``SchemaError`` reason."""
    encode = encode_unknown_effect(to_codec_json(schema), **options)

    def to_error(error: SchemaError) -> HttpBodyError:
        return HttpBodyError(SchemaErrorReason(error.issue), error.issue)

    def encode_body(value: T, content_type: str | None = None) -> Effect[Bytes, HttpBodyError, RE]:
        return (
            encode(value).map_error(to_error).flat_map(lambda encoded: json(encoded, content_type))
        )

    return encode_body

url_params

url_params(input, content_type=None) -> Bytes

The parameters form-encoded, application/x-www-form-urlencoded by default.

ParameterTypeDescription
input_url_params.Input
content_typestr | None = None

Returns Bytes

def url_params(input: _url_params.Input, content_type: str | None = None) -> Bytes:
    """The parameters form-encoded, ``application/x-www-form-urlencoded`` by
    default."""
    return text(_url_params.to_string(input), content_type or "application/x-www-form-urlencoded")

form_data

form_data(body) -> FormData
ParameterTypeDescription
bodyFormData

Returns FormData

def form_data(body: FormData) -> FormData:
    return body

form_data_record

form_data_record(entries) -> FormData

A form from a mapping; a sequence value adds one entry per item and None adds none.

ParameterTypeDescription
entriesFormDataInput

Returns FormData

def form_data_record(entries: FormDataInput) -> FormData:
    """A form from a mapping; a sequence value adds one entry per item and
    ``None`` adds none."""
    out: list[tuple[str, FormDataValue]] = []
    for key, value in entries.items():
        values = (
            cast("Sequence[FormDataCoercible]", value)
            if isinstance(value, (list, tuple))
            else (cast("FormDataCoercible", value),)
        )
        out.extend((key, _form_value(v)) for v in values if v is not None)
    return FormData(tuple(out))

stream

stream(body, content_type=None, content_length=None) -> Stream
ParameterTypeDescription
bodyStream_[bytes, object]
content_typestr | None = None
content_lengthint | None = None

Returns Stream

def stream(
    body: Stream_[bytes, object], content_type: str | None = None, content_length: int | None = None
) -> Stream:
    require_stream(body, "body")
    return Stream(body, content_type or "application/octet-stream", content_length)

file_from_info

file_from_info(path, info, *, bytes_to_read=None, chunk_size=None, offset=None, content_type=None) -> Effect[Stream, PlatformError, FileSystem]

A stream body of the file at path whose info is known.

ParameterTypeDescription
pathstr
infoFileInfo
bytes_to_readbyte_size.Input | None = None
chunk_sizeint | None = None
offsetbyte_size.Input | None = None
content_typestr | None = None

Returns Effect[Stream, PlatformError, FileSystem]

def file_from_info(
    path: str,
    info: FileInfo,
    *,
    bytes_to_read: byte_size.Input | None = None,
    chunk_size: int | None = None,
    offset: byte_size.Input | None = None,
    content_type: str | None = None,
) -> Effect[Stream, PlatformError, FileSystem]:
    """A stream body of the file at ``path`` whose ``info`` is known."""
    return FileSystem().flat_map(
        lambda fs: _file_body(
            fs,
            path,
            int(info.size),
            "fileFromInfo",
            bytes_to_read=bytes_to_read,
            chunk_size=chunk_size,
            offset=offset,
            content_type=content_type,
        )
    )

file

file(path, *, bytes_to_read=None, chunk_size=None, offset=None, content_type=None) -> Effect[Stream, PlatformError, FileSystem]

A stream body of the file at path, its length from stat.

ParameterTypeDescription
pathstr
bytes_to_readbyte_size.Input | None = None
chunk_sizeint | None = None
offsetbyte_size.Input | None = None
content_typestr | None = None

Returns Effect[Stream, PlatformError, FileSystem]

def file(
    path: str,
    *,
    bytes_to_read: byte_size.Input | None = None,
    chunk_size: int | None = None,
    offset: byte_size.Input | None = None,
    content_type: str | None = None,
) -> Effect[Stream, PlatformError, FileSystem]:
    """A stream body of the file at ``path``, its length from ``stat``."""
    return FileSystem().flat_map(
        lambda fs: fs.stat(path).flat_map(
            lambda info: _file_body(
                fs,
                path,
                int(info.size),
                "file",
                bytes_to_read=bytes_to_read,
                chunk_size=chunk_size,
                offset=offset,
                content_type=content_type,
            )
        )
    )

update_headers

update_headers(headers, body) -> Headers

headers with content-type / content-length matching body (removed for Empty and FormData).

ParameterTypeDescription
headersHeaders
bodyHttpBody

Returns Headers

def update_headers(headers: Headers, body: HttpBody) -> Headers:
    """``headers`` with ``content-type`` / ``content-length`` matching
    ``body`` (removed for ``Empty`` and ``FormData``)."""
    if isinstance(body, (Empty, FormData)):
        return headers.remove_many(("content-type", "content-length"))
    headers = (
        headers.remove("content-type")
        if body.content_type is None
        else headers.set("content-type", body.content_type)
    )
    return update_content_length(headers, body)

update_content_length

update_content_length(headers, body) -> Headers

headers with content-length matching body (removed for Empty, FormData and a body of unknown length).

ParameterTypeDescription
headersHeaders
bodyHttpBody

Returns Headers

def update_content_length(headers: Headers, body: HttpBody) -> Headers:
    """``headers`` with ``content-length`` matching ``body`` (removed for
    ``Empty``, ``FormData`` and a body of unknown length)."""
    length = None if isinstance(body, (Empty, FormData)) else body.content_length
    if length is None:
        return headers.remove("content-length")
    return headers.set("content-length", str(length))