Skip to main content

ApiClient

A client for one REST API, meant to be subclassed once per API.

Usage

Source

ApiClient(
    host_url=None,
    credential=None,
    scope=None,
    *,
    timeout=60,
    connect_timeout=30,
    max_tries=5,
    verbose=False,
    response_handler=None,
    transport=None,
    sleep=None
)

The class attributes say where the API is and where its credentials come from; __init__ arguments override them per instance. The credential is the credential argument, else app_credential() with the class’s variable names and mode when client_id_env and client_secret_env are set, else none (requests go unauthenticated). Wraps one httpx.Client; also a context manager, typed as the subclass.

Parameters

host_url: str | None = None

The API’s base URL; default the class’s host_url.

credential: TokenCredential | None = None

Any TokenCredential, such as DefaultAzureCredential() or RefreshTokenCredential; default chosen as above.

scope: str | None = None

The token scope; default the class’s scope, else f"{host_url}/.default".

timeout: float = 60

Seconds for the whole request.

connect_timeout: float = 30

Seconds to connect.

max_tries: int = 5

Attempts per request, the first included, for 429, 503 and connection failures.

verbose: bool = False

Log each request and response on the dazapiz.http logger at INFO, in azr’s coloured format through rich: method and URL, status, time and size, and the JSON request body and failed response body, abbreviated. Headers are never logged.

response_handler: Callable[[Any], Any] | None = None

Called with every non-empty parsed body; fetch() returns what it returns. fetch(parse=...) replaces it for one call.

transport: httpx.BaseTransport | None = None

The httpx transport requests go through; default httpx’s own. For tests: an httpx.MockTransport answers requests without a server.

sleep: Callable[[float], None] | None = None
Called with each retry wait, in seconds; default time.sleep. For tests: sleep=waits.append records the waits and does not wait.

Attributes

host_url: str or None

Class attribute: the API’s base URL.

scope: str or None

Class attribute: the token scope.

client_id_env: str or None

Class attribute: the variable holding the API’s service principal client ID, for app_credential().

client_secret_env: str or None

Class attribute: the variable holding its client secret.

tenant_id_env: str

Class attribute: the variable holding its tenant; "AZURE_TENANT_ID".

mode: str or None

Class attribute: app_credential()’s mode.

credential: TokenCredential or None
The credential the client uses, read-only (see credential).

Raises

ValueError
No host_url, or max_tries below 1; and what app_credential() raises.

Notes

Tokens come from credential.get_token(scope) through an httpx.Auth that keeps each token until five minutes before it expires. A 401 is not replayed (get_token() cannot be forced to refresh); the token is dropped, so the next request asks the credential again. A port of azr::api_client without its service and resource layers.

Examples

from dazapiz import ApiClient

class AppApiClient(ApiClient):
    host_url = "https://app-api.example.com"
    scope = "api://00000000-0000-0000-0000-000000000000/.default"
    client_id_env = "APP_API_CLIENT_ID"
    client_secret_env = "APP_API_SECRET"

    def get_item(self, item_id: str) -> dict:
        return self.fetch("/items/{item_id}", item_id=item_id)

with AppApiClient() as client:
    item = client.get_item("42")

Methods

Name Description
fetch() Send one request to path under the host URL and return the parsed body.
close() Close the underlying httpx.Client.

fetch()

Send one request to path under the host URL and return the parsed body.

Usage

Source

fetch(self, path: str, method: str = 'GET', query: Mapping[str, Any] | None = None, json: Any = None, headers: Mapping[str, str] | None = None, content_type: str | None = None, parse: None = None, path_params: str = {}) -> Any
fetch(self, path: str, method: str = 'GET', query: Mapping[str, Any] | None = None, json: Any = None, headers: Mapping[str, str] | None = None, content_type: str | None = None, parse: Callable[[Any], _T], path_params: str = {}) -> _T

429, 503 and connection failures are retried up to max_tries attempts, waiting Retry-After or backoff_default() (uniform in 1 to 2.5**attempt seconds, at most 60). A read timeout is not retried, since the server may have acted. The body is parsed by content_type, else the response’s: JSON (application/json, text/json, any +json) to Python objects, XML (application/xml, text/xml, any +xml) to an ElementTree.Element, anything else to str, an empty body to None; a non-empty result goes through response_handler.

Parameters
path: str

The path under the host URL, with {name} placeholders filled from path_params, URL-encoded. Never an absolute URL: the bearer token is only for the client’s host.

method: str = "GET"

The HTTP method, any case.

query: Mapping[str, Any] | None = None

Query parameters. A None value is left out, as azr’s req_url_query() drops NULL; so is a None in a list value.

json: Any = None

The body, sent as JSON. A pydantic model (anything with model_dump()) is sent as model_dump(mode="json", by_alias=True, exclude_unset=True), a dataclass instance field by field as dataclasses.asdict(), also when nested in lists, tuples, dict values or dataclass fields; logging shows the body as sent.

headers: Mapping[str, str] | None = None

Extra request headers.

content_type: str | None = None

Parse the body as this media type instead of the response’s Content-Type.

parse: Callable[[Any], Any] | None = None

Replaces response_handler for this call: called with the parsed body of every 2xx response, None for an empty one, and fetch() returns what it returns (typed so). Model.model_validate or TypeAdapter(list[Model]).validate_python validate the body.

**path_params: str
Values for the placeholders in path.
Returns
Any
The parsed body, or what parse or response_handler made of it.
Raises
ApiError

A non-2xx response, after any retries.

ResponseParseError

A JSON or XML body that does not parse, or an exception from parse, chained to it.

ValueError

A placeholder without a value, a value without a placeholder, a placeholder with a conversion or format spec ({id!r}, {id:>5}), or a path that is an absolute URL.

httpx.HTTPError
A connection failure after the last attempt, or a timeout.
Examples
sub = client.fetch("/subscriptions/{subscription_id}", subscription_id=sub_id)
pets = client.fetch(
    "/pet/findByStatus",
    query={"status": "sold"},
    parse=TypeAdapter(list[Pet]).validate_python,
)

close()

Close the underlying httpx.Client.

Usage

Source

close()

Called on leaving a with block.