Skip to content

API Reference

chumicro_requests

The error types every call can raise, the case-insensitive header dict, and the wire helpers (encode_request, parse_url, parse_charset, resolve_redirect_url, ResponseParser) for code that frames its own HTTP.

chumicro_requests

Non-blocking HTTP/1.1 client for CircuitPython, MicroPython, and CPython.

CaseInsensitiveDict

Header dict whose lookups fold to lowercase.

get(name, default=None)

Return the value for name or default if missing.

items()

Yield (original_name, value) pairs in insertion order.

add(name, value)

Append value to the existing header, joining with ,.

HttpBusyError

Bases: HttpError

Caller issued a request while another was still in flight.

HttpError

Bases: Exception

Base class for every chumicro-requests failure.

HttpOversizedError

Bases: HttpError

Response body exceeded max_body_bytes.

HttpProtocolError

Bases: HttpError

Server sent bytes the spec doesn't allow.

HttpTimeoutError

Bases: HttpError

Per-request timeout_ms budget elapsed before the response completed.

HttpURLError

Bases: HttpError

URL doesn't parse as a supported HTTP/HTTPS URL.

ParseState

Streaming response parser states.

ResponseParser

Streaming HTTP/1.1 response parser.

body property

Body bytes received so far (final once :attr:state is DONE).

__init__(*, max_body_bytes=DEFAULT_MAX_BODY_BYTES, max_header_bytes=DEFAULT_MAX_HEADER_BYTES, body_buffer=None, body_buffer_view=None, stream_body=False)

Construct the parser.

Parameters:

Name Type Description Default
max_body_bytes int

Cap on the buffered body size; ignored when stream_body is set.

DEFAULT_MAX_BODY_BYTES
max_header_bytes int

Cap on unparsed staged bytes outside the plain-body state, so it bounds the status line, headers, and chunked-framing lines.

DEFAULT_MAX_HEADER_BYTES
body_buffer bytearray | None

Optional caller-owned bytearray reused as the body buffer.

None
body_buffer_view memoryview | None

Pre-cached memoryview(body_buffer); required with body_buffer.

None
stream_body bool

When True, stage the body in a fixed window instead of buffering whole.

False

body_free()

Writable staging space in the streamed-body window, in bytes.

read_body_into(buffer)

Copy staged body bytes into caller-owned buffer; return the count.

discard_body()

Drop every staged body byte and reset both cursors.

feed(chunk)

Append chunk to the parser's buffer and advance the state.

feed_eof()

Signal that the peer closed the connection.

encode_request(method, host, path, *, headers=None, body=None, user_agent=None)

Encode an HTTP/1.1 request into bytes ready for the wire.

Parameters:

Name Type Description Default
method str

HTTP verb, sent verbatim.

required
host str

Value for the Host: header.

required
path str

Request-target, typically the URL path + query.

required
headers CaseInsensitiveDict | dict | list | tuple | None

Optional (name, value) pairs, dict, or CaseInsensitiveDict; override the defaults.

None
body bytes | None

Optional bytes body; adds Content-Length when set.

None
user_agent str | None

Override for the default User-Agent string.

None

Returns:

Type Description
bytes

Encoded request as bytes.

Raises:

Type Description
HttpURLError

A method, path, or header holds CR / LF / NUL or non-ASCII.

parse_charset(content_type)

Extract the charset=... parameter from a Content-Type header.

Parameters:

Name Type Description Default
content_type str | None

Raw Content-Type header value, or None.

required

Returns:

Type Description
str

The detected charset name, or "utf-8" as the safe default.

parse_url(url)

Split url into (scheme, host, port, path).

Parameters:

Name Type Description Default
url str

HTTP or HTTPS URL to split.

required

Returns:

Type Description
tuple[str, str, int, str]

4-tuple (scheme, host, port, path); path starts with /.

Raises:

Type Description
HttpURLError

Bad scheme, missing host, or non-integer port.

resolve_redirect_url(current_url, location)

Resolve a Location header value against the current request URL.

Parameters:

Name Type Description Default
current_url str

The URL of the request being redirected.

required
location str

The raw Location header value from the response.

required

Returns:

Type Description
str

Absolute URL the redirected request should target.

Raises:

Type Description
HttpURLError

current_url doesn't parse, or location is empty.

chumicro_requests.client

HttpClient itself, the RequestHandle each call returns, the Response it resolves to, and the WhenOversized policy for bodies past max_body_bytes. from chumicro_requests import HttpClient gives you the same class.

chumicro_requests.client

HTTP/1.1 client built on chumicro-sockets + chumicro-timing.

:class:HttpClient is the entry point.

WhenOversized

Policy for response bodies exceeding max_body_bytes.

Response

Result of a completed HTTP request.

Attributes:

Name Type Description
status_code

Integer HTTP status (e.g. 200).

reason

Reason phrase from the status line (e.g. "OK").

http_version

Protocol version string (e.g. "HTTP/1.1").

headers

:class:CaseInsensitiveDict of response headers.

body

Raw response body as bytes; empty when :attr:streamed.

url

The URL that was requested.

oversized_dropped

True when the body was dropped per the when_oversized policy.

streamed

True when issued with stream=True; the body is consumed incrementally.

encoding property writable

Charset used to decode :attr:body into :attr:text.

text property

:attr:body decoded to str using :attr:encoding.

Raises:

Type Description
UnicodeError

The body bytes don't match the encoding.

HttpError

The response is :attr:streamed, so has no whole body.

json()

Parse :attr:body as JSON and return the decoded object.

Raises:

Type Description
ValueError

The body is not valid JSON.

RequestHandle

Caller-visible handle to an in-flight (or completed) request.

result property

Return the :class:Response; raise the failure if any.

Raises:

Type Description
HttpError

The request failed, or result was read before done.

read_body_into(buffer)

Copy received body bytes into caller-owned buffer; return the count.

Raises:

Type Description
HttpError

The request was not issued with stream=True.

HttpClient

Non-blocking HTTP/1.1 client.

busy property

True while a request is in flight.

io_socket property

Underlying pollable socket while in flight, else None.

from_config(config, *, radio=None, ssl_context=None, transport_factory=None, **constructor_kwargs) classmethod

Build an :class:HttpClient from runtime config.

Config keys carry the deployment-varying values; any other constructor knob (buffer sizes, budgets, ticks) passes through verbatim as a keyword, and an explicit keyword wins over its config-derived value.

__init__(*, transport_factory, recv_budget_per_tick=DEFAULT_RECV_BUDGET_PER_TICK, max_body_bytes=DEFAULT_MAX_BODY_BYTES, max_header_bytes=DEFAULT_MAX_HEADER_BYTES, when_oversized=WhenOversized.DROP_WITH_EVENT, default_timeout_ms=DEFAULT_TIMEOUT_MS, default_max_redirects=DEFAULT_MAX_REDIRECTS, stream_buffer_size=DEFAULT_STREAM_BUFFER_SIZE, user_agent=None, ticks=None)

Wire up the client.

Parameters:

Name Type Description Default
transport_factory object

Callable (host, port, use_tls) opening a socket per hop.

required
recv_budget_per_tick int

Soft cap on bytes drained per :meth:handle call.

DEFAULT_RECV_BUDGET_PER_TICK
max_body_bytes int

Cap on a buffered body; not applied to stream=True.

DEFAULT_MAX_BODY_BYTES
max_header_bytes int

Cap on the response's unparsed header section.

DEFAULT_MAX_HEADER_BYTES
when_oversized str

Policy for over-cap responses (see :class:WhenOversized).

DROP_WITH_EVENT
default_timeout_ms int

Default per-request timeout in ms.

DEFAULT_TIMEOUT_MS
default_max_redirects int

Default cap on 3xx hops; 0 returns the 3xx as-is.

DEFAULT_MAX_REDIRECTS
stream_buffer_size int

Staging capacity in bytes for each stream=True body window.

DEFAULT_STREAM_BUFFER_SIZE
user_agent str | None

Override for the default User-Agent header.

None
ticks object | None

Optional chumicro_timing.ticks-shaped source; defaults to that submodule.

None

io_interest(now_ms)

Runner poll-interest bit for the current phase.

Read while receiving, write while sending, 0 otherwise.

next_deadline(now_ms)

Return the per-request timeout deadline, or None when idle.

request(method, url, *, body=None, json=None, headers=None, timeout_ms=None, max_redirects=None, on_done=None, stream=False)

Issue method against url; return a :class:RequestHandle.

Raises:

Type Description
HttpBusyError

A request is already in flight.

HttpURLError

url is not an absolute http/https URL.

ValueError

json= combined with body=.

TypeError

body is not bytes / bytearray / str.

get(url, *, headers=None, timeout_ms=None, max_redirects=None, on_done=None, stream=False)

Issue a GET request; return a :class:RequestHandle.

Raises the same exceptions as :meth:request.

post(url, *, body=None, json=None, headers=None, timeout_ms=None, max_redirects=None, on_done=None, stream=False)

Issue a POST request; return a :class:RequestHandle.

Raises the same exceptions as :meth:request.

put(url, *, body=None, json=None, headers=None, timeout_ms=None, max_redirects=None, on_done=None, stream=False)

Issue a PUT request; same body / json / stream semantics as :meth:post. Raises the same exceptions as :meth:request.

patch(url, *, body=None, json=None, headers=None, timeout_ms=None, max_redirects=None, on_done=None, stream=False)

Issue a PATCH request; same body / json / stream semantics as :meth:post. Raises the same exceptions as :meth:request.

delete(url, *, headers=None, timeout_ms=None, max_redirects=None, on_done=None, stream=False)

Issue a DELETE request; v1 sends no body.

Raises the same exceptions as :meth:request.

check(now_ms)

Return True while a request is in flight, so the runner ticks it.

handle(now_ms)

One tick of progress on the in-flight request.

cancel()

Abort the in-flight request; no-op when idle.

chumicro_requests.generators

Opt-in submodule for yield from flows driven by Runner.add_generator. fetch runs a whole request top to bottom and returns the Response; get / post / put / patch / delete are the per-verb forms. For a body too big for RAM, stream returns a BodyReader you pull one chunk per yield from. Import it explicitly; a program that never uses a generator never loads it.

chumicro_requests.generators

One-shot HTTP fetch and streamed-body reads as generators.

Public entry points: :func:fetch, :func:get, :func:post, :func:put, :func:patch, :func:delete, and :func:stream.

BodyReader

Streamed-body pull surface returned by :func:stream.

read_into(buffer)

Fill caller-owned buffer with body bytes; return the count.

Raises:

Type Description
HttpError

The request failed mid-body.

cancel()

Abort the transfer: close the socket, fail the handle.

fetch(transport_factory, method, url, *, headers=None, body=None, json=None, max_redirects=None, max_body_bytes=DEFAULT_MAX_BODY_BYTES, timeout_ms=DEFAULT_TIMEOUT_MS, user_agent=None, ticks=None)

Issue one HTTP request and return the :class:Response.

Parameters:

Name Type Description Default
transport_factory object

Callable (host, port, use_tls) -> connector (the HttpClient contract).

required
method str

HTTP verb, sent verbatim.

required
url str

Absolute http:// / https:// URL.

required
headers object | None

Optional dict / iterable of (name, value) pairs.

None
body object | None

Optional bytes / str body (mutually exclusive with json).

None
json object | None

Optional JSON body; sets Content-Type: application/json.

None
max_redirects int | None

Hops to follow before returning the 3xx as-is.

None
max_body_bytes int

Hard cap on the response body.

DEFAULT_MAX_BODY_BYTES
timeout_ms int

Deadline for the whole request, DNS lookup excluded.

DEFAULT_TIMEOUT_MS
user_agent str | None

Override the default User-Agent.

None
ticks object | None

Optional chumicro_timing-shaped tick source.

None

Returns:

Type Description
object

class:~chumicro_requests.client.Response.

Raises:

Type Description
HttpTimeoutError

The request exceeded timeout_ms (DNS stall excluded).

HttpOversizedError

Body exceeded max_body_bytes.

HttpProtocolError

Response was not valid HTTP/1.1 or peer closed mid-response.

HttpURLError

url or a redirect Location did not parse.

HttpError

The transport failed.

ValueError

Both body and json were given.

stream(transport_factory, method, url, *, headers=None, body=None, json=None, max_redirects=None, timeout_ms=DEFAULT_TIMEOUT_MS, stream_buffer_size=DEFAULT_STREAM_BUFFER_SIZE, user_agent=None, ticks=None)

Issue one request and return a :class:BodyReader for its body.

Raises:

Type Description
HttpTimeoutError

timeout_ms elapsed before headers arrived.

HttpProtocolError

The response was not valid HTTP/1.1.

HttpURLError

url or a redirect Location did not parse.

HttpError

The transport failed before headers arrived.

ValueError

Both body and json were given.

get(transport_factory, url, **kwargs)

One-shot GET; call as yield from get(transport_factory, url).

post(transport_factory, url, **kwargs)

One-shot POST; call as yield from post(transport_factory, url, json=...).

put(transport_factory, url, **kwargs)

One-shot PUT; call as yield from put(transport_factory, url, body=...).

patch(transport_factory, url, **kwargs)

One-shot PATCH; call as yield from patch(transport_factory, url, body=...).

delete(transport_factory, url, **kwargs)

One-shot DELETE; call as yield from delete(transport_factory, url).