API Reference
Protocols
Section titled âProtocolsâHTTPClientProtocol
Section titled âHTTPClientProtocolâProtocol for HTTP client implementations.
Start the HTTP client and its underlying connection pool.
Stop the HTTP client and release all connection resources.
Perform an arbitrary HTTP request.
| Parameter | Type | Description |
|---|---|---|
| `method` | str | HTTP method (GET, POST, PUT, âŚ). |
| `url` | str | Request URL. **kwargs: Additional options (headers, data, json, params, âŚ). |
| Type | Description |
|---|---|
| HttpResponse | Framework-owned HttpResponse. |
Perform GET request.
| Parameter | Type | Description |
|---|---|---|
| `url` | str | Request URL. **kwargs: Additional options. |
| Type | Description |
|---|---|
| HttpResponse | Framework-owned HttpResponse. |
Perform POST request.
| Parameter | Type | Description |
|---|---|---|
| `url` | str | Request URL. **kwargs: Additional options (e.g. ``json=``, ``data=``). |
| Type | Description |
|---|---|
| HttpResponse | Framework-owned HttpResponse. |
Perform PUT request.
| Parameter | Type | Description |
|---|---|---|
| `url` | str | Request URL. **kwargs: Additional options. |
| Type | Description |
|---|---|
| HttpResponse | Framework-owned HttpResponse. |
Perform DELETE request.
| Parameter | Type | Description |
|---|---|---|
| `url` | str | Request URL. **kwargs: Additional options. |
| Type | Description |
|---|---|
| HttpResponse | Framework-owned HttpResponse. |
Perform PATCH request.
| Parameter | Type | Description |
|---|---|---|
| `url` | str | Request URL. **kwargs: Additional options. |
| Type | Description |
|---|---|
| HttpResponse | Framework-owned HttpResponse. |
Perform HEAD request.
| Parameter | Type | Description |
|---|---|---|
| `url` | str | Request URL. **kwargs: Additional options. |
| Type | Description |
|---|---|
| HttpResponse | Framework-owned HttpResponse. |
InterceptorChainProtocol
Section titled âInterceptorChainProtocolâProtocol for interceptor chain management.
Manages a collection of interceptors and orchestrates their execution in sequence. Each interceptor in the chain processes the request/response before passing control to the next interceptor.
Example
class InterceptorChain: def __init__(self, interceptors: list[InterceptorProtocol]): self._interceptors = interceptors
async def execute_request(self, context: Any) -> Any: for interceptor in self._interceptors: context = await interceptor.intercept_request(context) return context
async def execute_response(self, response: Any) -> Any: for interceptor in reversed(self._interceptors): response = await interceptor.intercept_response(response) return responsedef add_interceptor(interceptor: InterceptorProtocol) -> None
Add an interceptor to the chain.
| Parameter | Type | Description |
|---|---|---|
| `interceptor` | InterceptorProtocol | The interceptor to add. |
def remove_interceptor(interceptor: InterceptorProtocol) -> None
Remove an interceptor from the chain.
| Parameter | Type | Description |
|---|---|---|
| `interceptor` | InterceptorProtocol | The interceptor to remove. |
Process request through the interceptor chain.
| Parameter | Type | Description |
|---|---|---|
| `context` | Any | Request context to process. |
| Type | Description |
|---|---|
| Any | Modified request context after all interceptors. |
Process response through the interceptor chain.
| Parameter | Type | Description |
|---|---|---|
| `response` | Any | Response to process. |
| Type | Description |
|---|---|
| Any | Modified response after all interceptors. |
InterceptorProtocol
Section titled âInterceptorProtocolâProtocol for request/response interceptors.
Interceptors are applied to every request/response cycle in
HTTPClient. Implementations receive typed
RequestContext objects and may modify them before the request is
dispatched, or inspect / annotate the raw response after it arrives.
Example
class LoggingInterceptor: async def intercept_request(self, context: Any) -> Any: logger.info(âoutbound_requestâ, method=context.method, url=context.url) return context
async def intercept_response(self, response: Any) -> Any: logger.info("inbound_response", status=response.status) return responseCalled before a request is dispatched.
| Parameter | Type | Description |
|---|---|---|
| `context` | Any | RequestContext for the outbound request. Implementations may mutate and return it. |
| Type | Description |
|---|---|
| Any | The (possibly modified) request context. |
Called after a response is received from the server.
| Parameter | Type | Description |
|---|---|---|
| `response` | Any | Raw response object from the underlying HTTP library. Implementations may annotate or replace it. |
| Type | Description |
|---|---|
| Any | The (possibly modified) response. |
Classes
Section titled âClassesâBaseURLHTTPClient
Section titled âBaseURLHTTPClientâAsync HTTP client with base-URL resolution and context-manager lifecycle.
Wraps HTTPClient and adds:
base_urlprepended to every relative request path.- Default headers merged into every request.
- Direct HttpResponse returns
from verb methods (raises on infrastructure failures rather than
returning
Result). - stream async context manager for line-oriented streaming responses (SSE, NDJSON).
- Lazy initialisation â no explicit
start()call required; the underlying connection pool is created on first request and torn down by close.
| Parameter | Type | Description |
|---|---|---|
| `base_url` | Base URL prepended to every relative path. | |
| `headers` | Default request headers merged with per-request headers. | |
| `timeout` | Request timeout in seconds (default 300). | |
| `name` | Logical name used in log messages. | |
| `retry` | Optional retry policy injected into the underlying HTTPClient. | |
| `circuit_breaker` | Optional circuit breaker injected into the underlying HTTPClient. |
Example
async with BaseURLHTTPClient( base_url="https://api.example.com/v1", headers={"Authorization": "Bearer token"}, timeout=60.0,) as client: resp = await client.post("/completions", json=payload) resp.raise_for_status()def __init__( base_url: str = '', headers: dict[str, str] | None = None, timeout: float = 300.0, name: str = 'base-url-http-client', retry: RetryPolicyProtocol | None = None, circuit_breaker: CircuitBreakerProtocol | None = None ) -> None
Stop the underlying HTTP client and release all connections.
Alias for close.
Make an HTTP request, returning HttpResponse directly.
Infrastructure failures are raised as exceptions (not wrapped in
Result). HTTP 4xx/5xx responses are returned as-is; call
raise_for_status
to convert them to exceptions when desired.
| Parameter | Type | Description |
|---|---|---|
| `method` | str | HTTP method (GET, POST, âŚ). |
| `url` | str | Relative path or absolute URL. **kwargs: Forwarded to aiohttp (``json=``, ``data=``, ``headers=``, âŚ). |
| Type | Description |
|---|---|
| HttpResponse | Framework HttpResponse. |
Perform a GET request.
| Parameter | Type | Description |
|---|---|---|
| `url` | str | Relative path or absolute URL. **kwargs: Forwarded to aiohttp. |
| Type | Description |
|---|---|
| HttpResponse | Framework HttpResponse. |
Perform a POST request.
| Parameter | Type | Description |
|---|---|---|
| `url` | str | Relative path or absolute URL. |
| `data` | Any | Optional body. ``dict`` is sent as JSON; other types as raw ``data``. Use ``json=`` kwarg for explicit JSON. **kwargs: Forwarded to aiohttp. |
| Type | Description |
|---|---|
| HttpResponse | Framework HttpResponse. |
Perform a PUT request.
| Parameter | Type | Description |
|---|---|---|
| `url` | str | Relative path or absolute URL. **kwargs: Forwarded to aiohttp. |
| Type | Description |
|---|---|
| HttpResponse | Framework HttpResponse. |
Perform a DELETE request.
| Parameter | Type | Description |
|---|---|---|
| `url` | str | Relative path or absolute URL. **kwargs: Forwarded to aiohttp. |
| Type | Description |
|---|---|
| HttpResponse | Framework HttpResponse. |
Perform a PATCH request.
| Parameter | Type | Description |
|---|---|---|
| `url` | str | Relative path or absolute URL. **kwargs: Forwarded to aiohttp. |
| Type | Description |
|---|---|
| HttpResponse | Framework HttpResponse. |
async def stream( method: str, url: str, **kwargs: Any ) -> AsyncIterator[StreamContext]
Async context manager for line-oriented streaming responses.
Opens a persistent HTTP connection and wraps the response in a StreamContext that exposes aiter_lines for consuming SSE / NDJSON streams â the dominant format used by LLM provider streaming APIs.
| Parameter | Type | Description |
|---|---|---|
| `method` | str | HTTP method (typically ``"POST"`` for LLM completions). |
| `url` | str | Relative path or absolute URL. **kwargs: Forwarded to aiohttp (``json=``, ``data=``, ``headers=``, âŚ). |
| Type | Description |
|---|---|
| AsyncIterator[StreamContext] | StreamContext with status, raise_for_status, and aiter_lines. |
Example
async with client.stream("POST", "/chat/completions", json=payload) as resp: resp.raise_for_status() async for line in resp.aiter_lines(): if line.startswith("data: "): ...ConnectionPool
Section titled âConnectionPoolâAsync HTTP connection pool backed by ``aiohttp``.
| Parameter | Type | Description |
|---|---|---|
| `max_connections` | Maximum total concurrent connections (default: 10). | |
| `max_keepalive_connections` | Keep-alive connections per host (default: 5). | |
| `timeout` | Request timeout in seconds (default: 30.0). | |
| `ttl_dns_cache` | DNS cache TTL in seconds (default: 300). | |
| `force_close` | Force-close connections after each use (default: False). | |
| `verify_ssl` | Verify SSL certificates (default: True). Set to ``False`` only in trusted internal networks â never in production for external endpoints. |
Example
pool = ConnectionPool(max_connections=100, timeout=60.0)await pool.start()response = await pool._session.get("https://api.example.com")await pool.stop()def __init__( max_connections: int = 10, max_keepalive_connections: int = 5, max_connections_per_host: int = 10, timeout: float = 30.0, ttl_dns_cache: int = 300, force_close: bool = False, verify_ssl: bool = True, proxy: str | None = None, trust_env: bool = True, cookie_jar: bool = True ) -> None
Initialise the connection pool and create the aiohttp session.
Close the connection pool and release all resources.
Return True if the pool session is active.
Pre-establish connections to known endpoints.
Fires a lightweight HEAD (falling back to GET) request to each
URL so that the TCP and TLS handshake has already been completed before
the first real request arrives. Errors are swallowed silently â this is
a best-effort optimisation, not a connectivity check.
| Parameter | Type | Description |
|---|---|---|
| `urls` | list[str] | Base URLs to pre-connect to (e.g. ``["https://api.example.com"]``). |
Example
await pool.start()await pool.warm_up(["https://api.example.com", "https://cdn.example.com"])ConnectionPoolConfig
Section titled âConnectionPoolConfigâConfiguration for the HTTP connection pool.
Attributes: max_connections: Maximum total concurrent connections (default: 10). max_keepalive_connections: Keep-alive connections per host (default: 5). max_connections_per_host: Maximum connections per individual host (default: 10). timeout: Request timeout in seconds (default: 30.0). ttl_dns_cache: DNS cache TTL in seconds (default: 300). force_close: Force-close connections after use (default: False).
HTTPClient
Section titled âHTTPClientâAsync HTTP client with connection pooling and optional resilience.
All dependencies are provided at construction time (constructor injection).
When used through HTTPProvider, retry_policy
and circuit_breaker are resolved from the container and injected here.
For standalone usage, pass them directly or accept the defaults.
| Parameter | Type | Description |
|---|---|---|
| `config` | Pool and client configuration. Defaults to HTTPClientConfig with framework defaults. | |
| `pool` | Optional pre-configured ConnectionPool. Created from *config* when not provided. | |
| `retry_policy` | Retry policy for transient failures. Defaults to a RetryPolicy with framework defaults. | |
| `circuit_breaker` | Optional circuit breaker; disabled when ``None``. | |
| `interceptors` | Zero or more interceptors applied to every request. | |
| `resilience` | Optional ResiliencePipelineProtocol that combines retry, circuit-breaker, bulkhead and timeout into a single composable pipeline. When provided it takes precedence over the individual ``retry_policy`` and ``circuit_breaker`` parameters. | |
| `metrics` | Optional MetricsRecorderProtocol for emitting ``http.request.duration`` (histogram) and ``http.request.status`` (counter) per-request metrics. |
Example
config = HTTPClientConfig() async with HTTPClient.session_context(config) as client: ⌠response = await client.get(âhttps://api.example.com/dataâ)
def __init__( config: HTTPClientConfig | None = None, pool: ConnectionPool | None = None, retry_policy: RetryPolicyProtocol | None = None, circuit_breaker: CircuitBreakerProtocol | None = None, interceptors: Iterable[InterceptorProtocol] = (), resilience: ResiliencePipelineProtocol | None = None, metrics: MetricsRecorderProtocol | None = None ) -> None
property config() -> HTTPClientConfig
Return the client configuration.
property pool() -> ConnectionPool
Return the underlying connection pool.
def pool(value: ConnectionPool) -> None
Replace the connection pool (mainly for testing).
Start the HTTP client and its connection pool.
Stop the HTTP client and close the connection pool.
Make an HTTP request with retry and optional circuit-breaker protection.
Note Infrastructure-level method â this method raises exceptions for all failures (circuit open, retries exhausted, connection errors). Use the high-level verb methods (get, post, etc.) in application/domain code â they return
Resultand avoid exception-based control flow for expected failures.
Summary of the two-layer strategy:
* ``request()`` â infrastructure layer, raises exceptions.* ``get()``, ``post()``, etc. â domain layer, return ``Result``.| Parameter | Type | Description |
|---|---|---|
| `method` | str | HTTP method (``GET``, ``POST``, etc.) |
| `url` | str | Target URL. **kwargs: Additional keyword arguments forwarded to ``aiohttp``. |
| Type | Description |
|---|---|
| HttpResponse | Framework-owned HttpResponse. |
| Exception | Description |
|---|---|
| HTTPCircuitOpenError | When the circuit breaker is open. |
| HTTPRetryExhaustedError | When all retry attempts are exhausted. |
| HTTPConnectionError | When the connection cannot be established. |
| HTTPTimeoutError | When the request times out. |
async def get( url: str, **kwargs: Any ) -> Result[HttpResponse, HTTPClientError]
Perform a GET request.
| Parameter | Type | Description |
|---|---|---|
| `url` | str | Target URL. **kwargs: Forwarded to request. |
| Type | Description |
|---|---|
| Result[HttpResponse, HTTPClientError] | ``Ok(HttpResponse)`` on 2xx; ``Err(HTTPStatusError)`` on 4xx/5xx; ``Err(HTTPConnectionError | HTTPTimeoutError)`` on transport failure. |
| Exception | Description |
|---|---|
| HTTPCircuitOpenError | When the circuit breaker is open. |
| HTTPRetryExhaustedError | When all retry attempts are exhausted. |
async def post( url: str, **kwargs: Any ) -> Result[HttpResponse, HTTPClientError]
Perform a POST request.
| Parameter | Type | Description |
|---|---|---|
| `url` | str | Target URL. **kwargs: Forwarded to request. |
| Type | Description |
|---|---|
| Result[HttpResponse, HTTPClientError] | ``Ok(HttpResponse)`` on 2xx; ``Err(HTTPStatusError)`` on 4xx/5xx; ``Err(HTTPConnectionError | HTTPTimeoutError)`` on transport failure. |
| Exception | Description |
|---|---|
| HTTPCircuitOpenError | When the circuit breaker is open. |
| HTTPRetryExhaustedError | When all retry attempts are exhausted. |
async def put( url: str, **kwargs: Any ) -> Result[HttpResponse, HTTPClientError]
Perform a PUT request.
| Parameter | Type | Description |
|---|---|---|
| `url` | str | Target URL. **kwargs: Forwarded to request. |
| Type | Description |
|---|---|
| Result[HttpResponse, HTTPClientError] | ``Ok(HttpResponse)`` on 2xx; ``Err(HTTPStatusError)`` on 4xx/5xx; ``Err(HTTPConnectionError | HTTPTimeoutError)`` on transport failure. |
| Exception | Description |
|---|---|
| HTTPCircuitOpenError | When the circuit breaker is open. |
| HTTPRetryExhaustedError | When all retry attempts are exhausted. |
async def delete( url: str, **kwargs: Any ) -> Result[HttpResponse, HTTPClientError]
Perform a DELETE request.
| Parameter | Type | Description |
|---|---|---|
| `url` | str | Target URL. **kwargs: Forwarded to request. |
| Type | Description |
|---|---|
| Result[HttpResponse, HTTPClientError] | ``Ok(HttpResponse)`` on 2xx; ``Err(HTTPStatusError)`` on 4xx/5xx; ``Err(HTTPConnectionError | HTTPTimeoutError)`` on transport failure. |
| Exception | Description |
|---|---|
| HTTPCircuitOpenError | When the circuit breaker is open. |
| HTTPRetryExhaustedError | When all retry attempts are exhausted. |
async def patch( url: str, **kwargs: Any ) -> Result[HttpResponse, HTTPClientError]
Perform a PATCH request.
| Parameter | Type | Description |
|---|---|---|
| `url` | str | Target URL. **kwargs: Forwarded to request. |
| Type | Description |
|---|---|
| Result[HttpResponse, HTTPClientError] | ``Ok(HttpResponse)`` on 2xx; ``Err(HTTPStatusError)`` on 4xx/5xx; ``Err(HTTPConnectionError | HTTPTimeoutError)`` on transport failure. |
| Exception | Description |
|---|---|
| HTTPCircuitOpenError | When the circuit breaker is open. |
| HTTPRetryExhaustedError | When all retry attempts are exhausted. |
async def head( url: str, **kwargs: Any ) -> Result[HttpResponse, HTTPClientError]
Perform a HEAD request.
| Parameter | Type | Description |
|---|---|---|
| `url` | str | Target URL. **kwargs: Forwarded to request. |
| Type | Description |
|---|---|
| Result[HttpResponse, HTTPClientError] | ``Ok(HttpResponse)`` on 2xx; ``Err(HTTPStatusError)`` on 4xx/5xx; ``Err(HTTPConnectionError | HTTPTimeoutError)`` on transport failure. |
| Exception | Description |
|---|---|
| HTTPCircuitOpenError | When the circuit breaker is open. |
| HTTPRetryExhaustedError | When all retry attempts are exhausted. |
async def post_multipart( url: str, fields: dict[str, str | bytes | tuple[str, bytes, str]], **kwargs: Any ) -> Result[HttpResponse, HTTPClientError]
Upload multipart/form-data.
Builds an aiohttp.FormData payload from fields and POSTs it.
Each value can be:
strâ sent as a plain text fieldbytesâ sent as a file-like binary field (filename inferred from the field name)(filename, data, content_type)â full control over the part headers
| Parameter | Type | Description |
|---|---|---|
| `url` | str | Target URL. |
| `fields` | dict[str, str | bytes | tuple[str, bytes, str]] | Mapping of field names to values. See above for supported value types. **kwargs: Additional keyword arguments forwarded to request. |
| Type | Description |
|---|---|
| Result[HttpResponse, HTTPClientError] | ``Ok(HttpResponse)`` on 2xx; ``Err(...)`` on failure. |
Example
result = await client.post_multipart( "https://api.example.com/upload", fields={ "description": "My file", "file": ("report.pdf", pdf_bytes, "application/pdf"), },)Async context manager that streams the response body as raw bytes chunks.
Unlike request, this method does not buffer the entire response body in memory â suitable for large file downloads or chunked responses.
| Parameter | Type | Description |
|---|---|---|
| `method` | str | HTTP method (``GET``, ``POST``, etc.) |
| `url` | str | Target URL. **kwargs: Additional keyword arguments forwarded to ``aiohttp``. |
| Type | Description |
|---|---|
| AsyncIterator[AsyncIterator[bytes]] | An AsyncIterator of ``bytes`` chunks. |
| Exception | Description |
|---|---|
| HTTPConnectionError | When the connection cannot be established. |
| HTTPTimeoutError | When the request times out. |
Example
async with client.stream("GET", large_file_url) as chunks: async for chunk in chunks: await file.write(chunk)Async context manager that consumes a Server-Sent Events (SSE) stream.
Opens a persistent GET connection and parses the text/event-stream
response into ServerSentEvent objects.
| Parameter | Type | Description |
|---|---|---|
| `url` | str | SSE endpoint URL. **kwargs: Additional keyword arguments forwarded to ``aiohttp``. |
| Type | Description |
|---|---|
| AsyncIterator[AsyncIterator[ServerSentEvent]] | An AsyncIterator of ServerSentEvent objects. |
| Exception | Description |
|---|---|
| HTTPConnectionError | When the connection cannot be established. |
Example
from lexigram.logging import get_logger
logger = get_logger(__name__)async with client.sse("https://api.example.com/events") as events: async for event in events: logger.info("sse_event", event_type=event.event, data=event.data)async def session_context( cls, config: HTTPClientConfig | None = None, retry_policy: RetryPolicyProtocol | None = None, circuit_breaker: CircuitBreakerProtocol | None = None, interceptors: Iterable[InterceptorProtocol] = () ) -> AsyncIterator[HTTPClient]
Async context manager that starts and stops the client automatically.
| Parameter | Type | Description |
|---|---|---|
| `config` | HTTPClientConfig | None | Optional HTTPClientConfig; framework defaults apply. |
| `retry_policy` | RetryPolicyProtocol | None | Optional retry policy; framework default when ``None``. |
| `circuit_breaker` | CircuitBreakerProtocol | None | Optional circuit breaker; disabled when ``None``. |
| `interceptors` | Iterable[InterceptorProtocol] | Zero or more interceptors. |
| Type | Description |
|---|---|
| AsyncIterator[HTTPClient] | A started HTTPClient instance. |
Example
async with HTTPClient.session_context() as client: ⌠response = await client.get(âhttps://api.example.comâ)
HTTPClientConfig
Section titled âHTTPClientConfigâTop-level configuration for HTTPClient.
Attributes:
pool: Connection pool settings.
proxy: Optional HTTP/HTTPS proxy URL (e.g. "http://proxy.example.com:8080").
Applied to all requests made by the client.
trust_env: Whether to read proxy settings from environment variables
(HTTP_PROXY, HTTPS_PROXY, NO_PROXY). Defaults to
True â set to False to ignore environment proxies.
cookie_jar: Whether to enable an in-memory cookie jar that persists
cookies across requests within a single HTTPClient session.
Defaults to True.
HTTPModule
Section titled âHTTPModuleâAsync outbound HTTP client backed by aiohttp with connection pooling.
Call configure to configure the HTTP client with custom settings and optional resilience integration (retry, circuit breaker).
Usage (defaults)
@module(imports=[HTTPModule.configure()])class AppModule(Module): passUsage (configured)
from lexigram.http.config import HTTPClientConfig
@module( imports=[HTTPModule.configure(HTTPClientConfig(timeout=30))])class AppModule(Module): passdef configure( cls, config: Any | None = None ) -> DynamicModule
Create an HTTPModule with explicit configuration.
| Parameter | Type | Description |
|---|---|---|
| `config` | Any | None | HTTPClientConfig or ``None`` for framework defaults. |
| Type | Description |
|---|---|
| DynamicModule | A DynamicModule descriptor. |
def stub(cls) -> DynamicModule
Return a no-op HTTPModule for unit testing.
Registers an HTTP client with default configuration. No real outbound connections are made unless explicitly called.
| Type | Description |
|---|---|
| DynamicModule | A DynamicModule with default HTTP client configuration. |
HTTPProvider
Section titled âHTTPProviderâFramework provider for the HTTP client.
Registers HTTPClient (and its HTTPClientProtocol binding) as a container-scoped singleton. Resilience dependencies are resolved from the container during boot and injected into the client â no service locator is used.
| Parameter | Type | Description |
|---|---|---|
| `config` | Optional HTTP client configuration. Framework defaults apply when not provided. |
def __init__(config: HTTPClientConfig | None = None) -> None
def from_config( cls, config: HTTPClientConfig, **context: Any ) -> Self
Create provider from config object.
async def register(container: ContainerRegistrarProtocol) -> None
Register HTTPClient bindings with the container.
| Parameter | Type | Description |
|---|---|---|
| `container` | ContainerRegistrarProtocol | The DI registrar. |
async def boot(container: ContainerResolverProtocol) -> None
Construct and start the HTTP client with injected resilience.
Resolves RetryPolicyProtocol and optionally
CircuitBreakerRegistryProtocol from the container. Falls back to
framework defaults when the container has no binding for them.
| Parameter | Type | Description |
|---|---|---|
| `container` | ContainerResolverProtocol | The DI resolver. |
Stop and dispose the HTTP client.
Return the health of the HTTP provider.
| Parameter | Type | Description |
|---|---|---|
| `timeout` | float | Unused; retained for interface compatibility. |
| Type | Description |
|---|---|
| HealthCheckResult | HealthCheckResult reflecting whether the client is active. |
HTTPRequestSentHook
Section titled âHTTPRequestSentHookâPayload fired when an outbound HTTP request is dispatched.
Attributes:
method: HTTP verb in upper-case (e.g. "GET").
url: Full URL of the outbound request.
HTTPResponseReceivedHook
Section titled âHTTPResponseReceivedHookâPayload fired when an outbound HTTP response is received.
Attributes: method: HTTP verb of the originating request. url: URL that was requested. status_code: HTTP status code of the received response.
RequestCompletedEvent
Section titled âRequestCompletedEventâHTTP request completed successfully.
Consumed by: request metrics, audit logging, performance analysis.
RequestContext
Section titled âRequestContextâContext information for an outbound HTTP request.
Used by interceptors to inspect and modify the request before it is sent.
Attributes: method: HTTP method (upper-cased). url: Target URL. headers: Request headers as a plain dict. service_name: Logical service name if known (service-mesh use cases). attempt: Current retry attempt number (0-indexed). start_time: Timestamp when the request was initiated.
RequestRetryExhaustedEvent
Section titled âRequestRetryExhaustedEventâHTTP request exhausted all retry attempts.
Consumed by: retry management, circuit breaker logic, error reporting.
RequestTimeoutEvent
Section titled âRequestTimeoutEventâHTTP request timed out before completion.
Consumed by: timeout tracking, performance monitoring, alerting.
ResponseContext
Section titled âResponseContextâContext information for a received HTTP response.
Used by interceptors to inspect response metadata.
Attributes:
status: HTTP status code.
headers: Response headers.
content_length: Optional response body length in bytes.
duration: Round-trip duration in seconds.
success: True when status < 400.
error: Human-readable error message when the request failed.
StreamContext
Section titled âStreamContextâWraps an aiohttp response for line-oriented streaming.
Exposes status, raise_for_status(), and aiter_lines() without leaking the underlying aiohttp type to callers.
| Parameter | Type | Description |
|---|---|---|
| `resp` | The raw aiohttp ClientResponse, owned by the enclosing context manager for the duration of the stream. |
HTTP status code of the response.
Raise HttpStatusError for 4xx/5xx.
| Exception | Description |
|---|---|
| HttpStatusError | When the status code is 400 or higher. |
Yield decoded text lines from the streaming response body.
| Type | Description |
|---|---|
| AsyncIterator[str] | Each line decoded from UTF-8 with trailing CR/LF stripped. |
Functions
Section titled âFunctionsâbuild_url
Section titled âbuild_urlâ
Build a complete URL from base, path, and query parameters.
| Parameter | Type | Description |
|---|---|---|
| `base` | str | Base URL (e.g. ``"https://api.example.com"``). |
| `path` | str | URL path to append (e.g. ``"/users/123"``). |
| `params` | dict[str, Any] | None | Optional query parameters; ``None`` values are omitted. |
| Type | Description |
|---|---|
| str | Complete URL with path and encoded query string. |
Example
build_url(âhttps://api.example.comâ, â/usersâ, {âpageâ: 1}) âhttps://api.example.com/users?page=1â
extract_json_type
Section titled âextract_json_typeâ
Extract the JSON MIME type from a Content-Type header value.
| Parameter | Type | Description |
|---|---|---|
| `content_type` | str | Raw ``Content-Type`` header value. |
| Type | Description |
|---|---|
| str | None | The base MIME type if it contains ``"json"``, otherwise ``None``. |
Example
extract_json_type(âapplication/json; charset=utf-8â) âapplication/jsonâ extract_json_type(âtext/htmlâ) None
format_timeout
Section titled âformat_timeoutâ
Format a timeout value for human-readable display.
| Parameter | Type | Description |
|---|---|---|
| `timeout` | float | None | Timeout in seconds, or ``None`` for no timeout. |
| Type | Description |
|---|---|
| str | Formatted string such as ``"30.0s"`` or ``"no timeout"``. |
merge_headers
Section titled âmerge_headersâ
Merge multiple header mappings; later entries win on duplicate keys.
| Parameter | Type | Description |
|---|---|---|
| `normalize` | bool | When ``True``, lowercase keys and strip values (default). |
| Type | Description |
|---|---|
| dict[str, str] | Merged ``dict[str, str]``. |
parse_headers
Section titled âparse_headersâ
Normalise HTTP headers: lowercase keys, strip whitespace from values.
| Parameter | Type | Description |
|---|---|---|
| `headers` | Mapping[str, Any] | Any mapping of header values. |
| Type | Description |
|---|---|
| dict[str, str] | Normalised ``dict[str, str]``. |
Example
parse_headers({âContent-Typeâ: â application/json â}) {âcontent-typeâ: âapplication/jsonâ}
parse_url_parts
Section titled âparse_url_partsâ
Parse a URL into its component parts.
| Parameter | Type | Description |
|---|---|---|
| `url` | str | Full URL to parse. |
| Type | Description |
|---|---|
| dict[str, Any] | Dictionary with keys ``scheme``, ``host``, ``port``, ``path``, ``params``, ``fragment``. |
validate_host
Section titled âvalidate_hostâ
Validate a hostname or IPv4 address.
| Parameter | Type | Description |
|---|---|---|
| `host` | str | Hostname or IP address to validate. |
| Exception | Description |
|---|---|
| HTTPError | If the host is empty or has an invalid format. |
validate_port
Section titled âvalidate_portâ
Validate a TCP port number.
| Parameter | Type | Description |
|---|---|---|
| `port` | int | Port number (must be 1â65535). |
| Exception | Description |
|---|---|
| HTTPError | If the port is not an integer or is out of range. |
validate_positive_int
Section titled âvalidate_positive_intâ
Validate that value is a positive integer.
| Parameter | Type | Description |
|---|---|---|
| `value` | int | Integer to validate. |
| `field` | str | Field name used in the error message. |
| Exception | Description |
|---|---|
| HTTPError | If ``value`` is not a positive integer. |
validate_timeout
Section titled âvalidate_timeoutâ
Validate a timeout value.
| Parameter | Type | Description |
|---|---|---|
| `timeout` | float | None | Timeout in seconds, or ``None`` for no timeout. |
| Exception | Description |
|---|---|
| HTTPError | If ``timeout`` is not a positive number. |
validate_url
Section titled âvalidate_urlâ
Validate a URL string.
| Parameter | Type | Description |
|---|---|---|
| `url` | str | URL to validate. |
| `require_scheme` | bool | When ``True``, ``http``/``https`` scheme is required. |
| Exception | Description |
|---|---|
| HTTPError | If the URL is missing, malformed, or missing a required scheme. |
Exceptions
Section titled âExceptionsâHTTPCircuitOpenError
Section titled âHTTPCircuitOpenErrorâRaised when the circuit breaker is open and requests are rejected.
HTTPClientError
Section titled âHTTPClientErrorâBase exception for all HTTP client errors.
HTTPConnectionError
Section titled âHTTPConnectionErrorâRaised when a connection to a remote host fails.
HTTPInterceptorError
Section titled âHTTPInterceptorErrorâRaised when a request/response interceptor fails.
HTTPRetryExhaustedError
Section titled âHTTPRetryExhaustedErrorâRaised when all retry attempts for a request have been exhausted.
HTTPTimeoutError
Section titled âHTTPTimeoutErrorâRaised when a connection or request times out.