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
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 | |
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
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 | |
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 |