HTTP¶
utils ¶
Reusable HTTP utilities for t3api-utils (sync + async).
Scope (by design)¶
Configures and performs network activity (clients, retries, JSON handling, headers, SSL, proxies)
Highlights¶
- Centralized
httpxclient builders (sync + async) with sane defaults (timeout, HTTP/2, SSL viacertifi, base headers, optional proxies). - Lightweight retry policy with exponential backoff + jitter.
- Standard JSON request helpers with consistent error text.
- Simple helpers to attach/remove Bearer tokens without performing auth.
- Optional request/response logging hooks.
Examples¶
Sync client with bearer token: from t3api_utils.http import build_client, set_bearer_token, request_json
client = build_client()
set_bearer_token(client=client, token="<token>")
data = request_json(client=client, method="GET", url="/v2/auth/whoami")
Async with logging hooks
from t3api_utils.http import build_async_client, arequest_json, LoggingHooks
hooks = LoggingHooks(enabled=True) async with build_async_client(hooks=hooks) as aclient: data = await arequest_json(aclient=aclient, method="GET", url="/healthz")
HTTPConfig
dataclass
¶
HTTPConfig(host: str = _get_default_host(), timeout: float = DEFAULT_TIMEOUT, verify_ssl: Union[bool, str] = certifi.where(), base_headers: Mapping[str, str] = (lambda: {'User-Agent': DEFAULT_USER_AGENT})(), proxies: Optional[Union[str, Mapping[str, str]]] = None)
Base HTTP client configuration (no routes).
Attributes:
| Name | Type | Description |
|---|---|---|
host |
str
|
Base URL of the API server (e.g. |
timeout |
float
|
Request timeout in seconds. Defaults to |
verify_ssl |
Union[bool, str]
|
SSL verification setting. Pass |
base_headers |
Mapping[str, str]
|
Default headers attached to every request built by
this configuration. Defaults to a |
proxies |
Optional[Union[str, Mapping[str, str]]]
|
Optional proxy URL string or mapping of scheme to proxy
URL (e.g. |
RetryPolicy
dataclass
¶
RetryPolicy(max_attempts: int = 3, backoff_factor: float = 0.5, retry_methods: Sequence[str] = ('GET', 'HEAD', 'OPTIONS', 'DELETE', 'PUT', 'PATCH', 'POST'), retry_statuses: Sequence[int] = (408, 409, 425, 429, 500, 502, 503, 504))
Retry policy for transient failures. Route-agnostic.
Note: writes (POST/PUT/PATCH/DELETE) are included by default. If your call is not idempotent, provide a custom policy at the callsite.
Attributes:
| Name | Type | Description |
|---|---|---|
max_attempts |
int
|
Maximum number of attempts (including the initial
request). Defaults to |
backoff_factor |
float
|
Base delay in seconds for exponential backoff.
Actual sleep is |
retry_methods |
Sequence[str]
|
HTTP methods eligible for automatic retry. Defaults to all standard methods. |
retry_statuses |
Sequence[int]
|
HTTP status codes that trigger a retry. Defaults to common transient-error codes (408, 409, 425, 429, 500, 502, 503, 504). |
LoggingHooks
dataclass
¶
LoggingHooks(enabled: bool = False, log_headers: bool = True, log_body: bool = True, file_path: Optional[str] = None)
Optional request/response logging via httpx event hooks.
Attributes:
| Name | Type | Description |
|---|---|---|
enabled |
bool
|
When |
log_headers |
bool
|
When |
log_body |
bool
|
When |
file_path |
Optional[str]
|
Optional file path for HTTP debug logs. The file is opened in write mode (truncated) on first use. |
from_env
classmethod
¶
Create a LoggingHooks instance configured from environment variables.
Reads T3_LOG_HTTP, T3_LOG_HEADERS, T3_LOG_BODY, and
T3_LOG_FILE from the environment.
Returns:
| Type | Description |
|---|---|
LoggingHooks
|
A configured |
LoggingHooks
|
not set or is falsy, returns a disabled instance. |
Source code in t3api_utils/http/utils.py
as_hooks ¶
Build an httpx event_hooks mapping for request/response logging.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
async_client
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
Optional[Dict[str, Any]]
|
A dict with |
Optional[Dict[str, Any]]
|
|
Source code in t3api_utils/http/utils.py
T3HTTPError ¶
Bases: HTTPError
Raised when a request fails permanently or response parsing fails.
Initialize a T3HTTPError.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Human-readable description of the failure. |
required |
response
|
Optional[Response]
|
The |
None
|
Source code in t3api_utils/http/utils.py
status_code
property
¶
HTTP status code from the stored response, or None if unavailable.
build_client ¶
build_client(*, config: Optional[HTTPConfig] = None, headers: Optional[Mapping[str, str]] = None, hooks: Optional[LoggingHooks] = None) -> httpx.Client
Construct a configured httpx.Client with sane defaults.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
Optional[HTTPConfig]
|
HTTP configuration (host, timeout, SSL, proxies).
Defaults to |
None
|
headers
|
Optional[Mapping[str, str]]
|
Extra headers merged on top of |
None
|
hooks
|
Optional[LoggingHooks]
|
Optional logging hooks attached as httpx event hooks. |
None
|
Returns:
| Type | Description |
|---|---|
Client
|
A ready-to-use |
Source code in t3api_utils/http/utils.py
build_async_client ¶
build_async_client(*, config: Optional[HTTPConfig] = None, headers: Optional[Mapping[str, str]] = None, hooks: Optional[LoggingHooks] = None) -> httpx.AsyncClient
Construct a configured httpx.AsyncClient with sane defaults.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
Optional[HTTPConfig]
|
HTTP configuration (host, timeout, SSL, proxies).
Defaults to |
None
|
headers
|
Optional[Mapping[str, str]]
|
Extra headers merged on top of |
None
|
hooks
|
Optional[LoggingHooks]
|
Optional logging hooks attached as httpx event hooks. |
None
|
Returns:
| Type | Description |
|---|---|
AsyncClient
|
A ready-to-use |
AsyncClient
|
an async context manager or closed explicitly when finished. |
Source code in t3api_utils/http/utils.py
request_json ¶
request_json(*, client: Client, method: str, url: str, params: Optional[Mapping[str, Any]] = None, json_body: Optional[Any] = None, files: Optional[RequestFiles] = None, headers: Optional[Mapping[str, str]] = None, policy: Optional[RetryPolicy] = None, expected_status: Union[int, Iterable[int]] = (200, 201, 202, 204), timeout: Optional[Union[float, Timeout]] = None, request_id: Optional[str] = None) -> Any
Issue a synchronous JSON request with automatic retries.
Sends the request via the provided httpx.Client, retrying on
transient failures according to the supplied (or default) retry
policy. The response body is parsed as JSON and returned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
Client
|
An |
required |
method
|
str
|
HTTP method (e.g. |
required |
url
|
str
|
Request URL or path (resolved against the client's base URL). |
required |
params
|
Optional[Mapping[str, Any]]
|
Optional query-string parameters. |
None
|
json_body
|
Optional[Any]
|
Optional JSON-serializable request body. Mutually exclusive with files. |
None
|
files
|
Optional[RequestFiles]
|
Optional multipart file upload data. Mutually exclusive
with json_body. Accepts the same formats as |
None
|
headers
|
Optional[Mapping[str, str]]
|
Optional per-request headers merged on top of the client's default headers. |
None
|
policy
|
Optional[RetryPolicy]
|
Retry policy. Defaults to |
None
|
expected_status
|
Union[int, Iterable[int]]
|
Status code(s) considered successful. Defaults
to |
(200, 201, 202, 204)
|
timeout
|
Optional[Union[float, Timeout]]
|
Per-request timeout override. |
None
|
request_id
|
Optional[str]
|
Optional value set as the |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Parsed JSON response body, or |
Raises:
| Type | Description |
|---|---|
ValueError
|
If both json_body and files are provided. |
T3HTTPError
|
If the response status is not in expected_status after all retries are exhausted, or if the response body cannot be decoded as JSON. |
Source code in t3api_utils/http/utils.py
request_bytes ¶
request_bytes(*, client: Client, method: str, url: str, params: Optional[Mapping[str, Any]] = None, json_body: Optional[Any] = None, files: Optional[RequestFiles] = None, headers: Optional[Mapping[str, str]] = None, policy: Optional[RetryPolicy] = None, expected_status: Union[int, Iterable[int]] = (200, 201, 202, 204), timeout: Optional[Union[float, Timeout]] = None, request_id: Optional[str] = None) -> bytes
Issue a synchronous request and return the response body as bytes.
Same retry and error handling as :func:request_json, but returns
raw bytes instead of parsing JSON. Useful for downloading PDFs,
images, and other binary content.
Returns:
| Type | Description |
|---|---|
bytes
|
Response body as |
Source code in t3api_utils/http/utils.py
request_text ¶
request_text(*, client: Client, method: str, url: str, params: Optional[Mapping[str, Any]] = None, json_body: Optional[Any] = None, files: Optional[RequestFiles] = None, headers: Optional[Mapping[str, str]] = None, policy: Optional[RetryPolicy] = None, expected_status: Union[int, Iterable[int]] = (200, 201, 202, 204), timeout: Optional[Union[float, Timeout]] = None, request_id: Optional[str] = None) -> str
Issue a synchronous request and return the response body as text.
Same retry and error handling as :func:request_json, but returns
decoded text instead of parsing JSON. Useful for CSV, HTML, and
other text content.
Returns:
| Type | Description |
|---|---|
str
|
Response body as |
Source code in t3api_utils/http/utils.py
request_raw ¶
request_raw(*, client: Client, method: str, url: str, params: Optional[Mapping[str, Any]] = None, json_body: Optional[Any] = None, files: Optional[RequestFiles] = None, headers: Optional[Mapping[str, str]] = None, policy: Optional[RetryPolicy] = None, expected_status: Union[int, Iterable[int]] = (200, 201, 202, 204), timeout: Optional[Union[float, Timeout]] = None, request_id: Optional[str] = None) -> httpx.Response
Issue a synchronous request and return the raw httpx.Response.
Same retry and error handling as :func:request_json, but returns
the full response object for callers that need access to headers,
content-type, or streaming.
Returns:
| Type | Description |
|---|---|
Response
|
The validated |
Source code in t3api_utils/http/utils.py
arequest_json
async
¶
arequest_json(*, aclient: AsyncClient, method: str, url: str, params: Optional[Mapping[str, Any]] = None, json_body: Optional[Any] = None, files: Optional[RequestFiles] = None, headers: Optional[Mapping[str, str]] = None, policy: Optional[RetryPolicy] = None, expected_status: Union[int, Iterable[int]] = (200, 201, 202, 204), timeout: Optional[Union[float, Timeout]] = None, request_id: Optional[str] = None) -> Any
Issue an asynchronous JSON request with automatic retries.
Async equivalent of :func:request_json. Sends the request via the
provided httpx.AsyncClient, retrying on transient failures
according to the supplied (or default) retry policy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
aclient
|
AsyncClient
|
An |
required |
method
|
str
|
HTTP method (e.g. |
required |
url
|
str
|
Request URL or path (resolved against the client's base URL). |
required |
params
|
Optional[Mapping[str, Any]]
|
Optional query-string parameters. |
None
|
json_body
|
Optional[Any]
|
Optional JSON-serializable request body. Mutually exclusive with files. |
None
|
files
|
Optional[RequestFiles]
|
Optional multipart file upload data. Mutually exclusive
with json_body. Accepts the same formats as |
None
|
headers
|
Optional[Mapping[str, str]]
|
Optional per-request headers merged on top of the client's default headers. |
None
|
policy
|
Optional[RetryPolicy]
|
Retry policy. Defaults to |
None
|
expected_status
|
Union[int, Iterable[int]]
|
Status code(s) considered successful. Defaults
to |
(200, 201, 202, 204)
|
timeout
|
Optional[Union[float, Timeout]]
|
Per-request timeout override. |
None
|
request_id
|
Optional[str]
|
Optional value set as the |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Parsed JSON response body, or |
Raises:
| Type | Description |
|---|---|
ValueError
|
If both json_body and files are provided. |
T3HTTPError
|
If the response status is not in expected_status after all retries are exhausted, or if the response body cannot be decoded as JSON. |
Source code in t3api_utils/http/utils.py
arequest_bytes
async
¶
arequest_bytes(*, aclient: AsyncClient, method: str, url: str, params: Optional[Mapping[str, Any]] = None, json_body: Optional[Any] = None, files: Optional[RequestFiles] = None, headers: Optional[Mapping[str, str]] = None, policy: Optional[RetryPolicy] = None, expected_status: Union[int, Iterable[int]] = (200, 201, 202, 204), timeout: Optional[Union[float, Timeout]] = None, request_id: Optional[str] = None) -> bytes
Async equivalent of :func:request_bytes.
Source code in t3api_utils/http/utils.py
arequest_text
async
¶
arequest_text(*, aclient: AsyncClient, method: str, url: str, params: Optional[Mapping[str, Any]] = None, json_body: Optional[Any] = None, files: Optional[RequestFiles] = None, headers: Optional[Mapping[str, str]] = None, policy: Optional[RetryPolicy] = None, expected_status: Union[int, Iterable[int]] = (200, 201, 202, 204), timeout: Optional[Union[float, Timeout]] = None, request_id: Optional[str] = None) -> str
Async equivalent of :func:request_text.
Source code in t3api_utils/http/utils.py
arequest_raw
async
¶
arequest_raw(*, aclient: AsyncClient, method: str, url: str, params: Optional[Mapping[str, Any]] = None, json_body: Optional[Any] = None, files: Optional[RequestFiles] = None, headers: Optional[Mapping[str, str]] = None, policy: Optional[RetryPolicy] = None, expected_status: Union[int, Iterable[int]] = (200, 201, 202, 204), timeout: Optional[Union[float, Timeout]] = None, request_id: Optional[str] = None) -> httpx.Response
Async equivalent of :func:request_raw.
Source code in t3api_utils/http/utils.py
set_bearer_token ¶
Attach or replace the Authorization: Bearer header on a client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
Union[Client, AsyncClient]
|
Sync or async |
required |
token
|
str
|
Raw bearer token string (without the |
required |
Source code in t3api_utils/http/utils.py
clear_bearer_token ¶
Remove the Authorization header from a client, if present.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
Union[Client, AsyncClient]
|
Sync or async |
required |