HTTPClient¶
canfar.client.HTTPClient is the lower-level transport used by the Session,
Image, Context, and Overview clients. It composes native synchronous and
asynchronous httpx2 clients and is useful when an application needs a CANFAR
request outside those higher-level modules.
Construct a client¶
from canfar.client import HTTPClient
from canfar.models.config import Configuration
client = HTTPClient(
config=Configuration(),
timeout=60,
concurrency=64,
)
The main settings are:
url: an explicit Science Platform Server URL.config: the persistedConfigurationto resolve by default.authentication_idp: a transient Identity Provider selector for this client.token: a runtime bearer token.certificate: a runtime X.509 certificate path.timeout: HTTP request inactivity timeout in seconds, from 1 to 300 with a default of 30, not a total job deadline.concurrency: maximum async connection count, from 1 to 128.transport: anhttpx2transport you own, to share one connection pool across clients. This is a keyword argument only.
Async requests wait for a free connection without a
pool timeout. Connect, read, and write timeouts still use timeout, and
concurrency still limits connections. Synchronous pool waits also use timeout.
Share a connection pool¶
A service that calls the Science Platform for many users can pass one
transport to every client. Use an httpx2.BaseTransport for synchronous
requests and an httpx2.AsyncBaseTransport for asynchronous ones; a mismatch
raises TypeError. Closing a client leaves the transport open, so close it
yourself when your service stops. Connection limits come from the transport,
not concurrency; timeout still applies to each request.
import httpx2
from canfar.sessions import Session
transport = httpx2.HTTPTransport(limits=httpx2.Limits(max_connections=64))
for token in user_tokens:
with Session(
token=token,
url="https://ws-uv.canfar.net/skaha/v1",
transport=transport,
) as session:
print(session.fetch())
transport.close()
A transport works with bearer tokens only. Combining it with a runtime
certificate or a saved X.509 Authentication Record raises ValueError, because
httpx2 would otherwise drop the client certificate. No environment variable
sets the transport.
When no explicit url is supplied, the active Server Selection in
Configuration supplies the Science Platform Server. Without a runtime
credential, authentication_idp selects a saved Authentication Record for this
client; otherwise the active Authentication Record is used.
Credential precedence and lifecycle¶
Runtime credentials take precedence over saved Authentication Records. A
non-empty runtime token wins over a saved X.509 or OIDC record; a runtime
certificate likewise wins. An empty runtime token is treated as absent: a supplied runtime certificate
still takes precedence, otherwise the client uses the selected saved record. Runtime credentials are not persisted.
Without runtime credentials, the client resolves the selected saved record when its sync or async HTTPX2 client is first created. An expired OIDC record is refreshed through the saved Authentication Record and the refreshed token is persisted. If the record cannot refresh or an X.509 certificate is invalid, client construction/request setup raises the established authentication error instead of silently sending an unauthenticated request.
Use the native context manager that matches the transport:
from canfar.client import HTTPClient
with HTTPClient(token="runtime-token", url="https://example.test/skaha/v1") as client:
response = client.client.get("context")
async def request() -> None:
async with HTTPClient(
token="runtime-token",
url="https://example.test/skaha/v1",
) as client:
response = await client.asynclient.get("context")
client is the native httpx2.Client; asynclient is the native
httpx2.AsyncClient. They are created lazily and closed by their matching
context manager. Do not use the async client from synchronous code or expect a
sync client to run through an event loop.
Errors and logging¶
HTTP response hooks raise httpx2.HTTPStatusError by default for unsuccessful
responses. Catch it at the application boundary when a request can fail:
from httpx2 import HTTPStatusError
from canfar.client import HTTPClient
with HTTPClient(token="runtime-token", url="https://example.test/skaha/v1") as client:
try:
response = client.client.get("invalid-endpoint")
except HTTPStatusError as exc:
print(exc.response.status_code)
Authentication and configuration failures use CANFAR's authentication/error types. Do not log tokens, certificates, or raw credential records. Configure the application logger explicitly when diagnostics are needed:
from canfar import configure_logging
configure_logging("debug")
Configuration editing¶
HTTPClient consumes the persisted Configuration; it does not own edits or
alternate configuration services. Use config.editor.get(), set(), and
save() to make validated, atomic changes while preserving the stable
version/active/authentication/servers/registry/console shape. See
Install and set up.
API reference¶
canfar.client.HTTPClient ¶
Bases: BaseSettings
HTTP Client for interacting with CANFAR Science Platform services (V2).
This client uses a composition-based approach and inherits from Pydantic's BaseSettings to allow for flexible configuration via arguments, environment variables, or a configuration file.
The client prioritizes credentials in the following order:
- Runtime Arguments/Environment Variables: A
tokenorcertificateprovided at instantiation (e.g.,CANFAR_TOKEN="..."). - Saved Authentication: The Authentication Record named by transient
authentication_idporactive.authentication, plus the active Server Selection when no expliciturlis supplied.
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If configuration is invalid. |
client
property
¶
client: Client
Get the synchronous HTTPX2 Client.
| RETURNS | DESCRIPTION |
|---|---|
Client
|
The synchronous HTTPX2 client.
TYPE:
|
uses_runtime_credentials
property
¶
uses_runtime_credentials: bool
Return whether runtime token or certificate credentials are active.
authentication_record
property
¶
authentication_record: AuthenticationCredential | None
Return this client's selected usable Authentication Record, if any.
build
classmethod
¶
build(
*,
config: Configuration,
authentication_idp: str,
url: Any,
token: Any = None,
certificate: Any = None,
**extra: Any,
) -> Self
Build a client, omitting runtime credentials that were not supplied.
Unset credentials are omitted rather than passed as None so the
settings sources stay free to supply them.
| PARAMETER | DESCRIPTION |
|---|---|
config
|
Configuration backing the client.
TYPE:
|
authentication_idp
|
Canonical Identity Provider key.
TYPE:
|
url
|
Base URL for the client.
TYPE:
|
token
|
Runtime bearer token, when overriding the saved record.
TYPE:
|
certificate
|
Runtime X.509 certificate path, when overriding it.
TYPE:
|
**extra
|
Further client settings passed through unchanged.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Self
|
A client of the calling class bound to the supplied credentials. |