Connect, Authenticate and Write Your Own Transport

The client does not depend on any HTTP library. It builds the requests and parses the responses, and leaves sending them over the wire to a transport. The transport also takes care of everything around the connection: the authentication, the certificates, the proxies, the timeouts and the retries.

The Ready-Made Transport

aas_client3_2.requests_transport.RequestsTransport sends the requests through a requests.Session, which you configure as usual with requests:

import contextlib
import dataclasses
from typing import Iterator

import requests

from aas_client3_2 import (
    http as aas_client_http,
    requests_transport as aas_client_requests_transport,
    submodel_repository as aas_client_submodel_repository,
)

session = requests.Session()

# Basic authentication, or any other authentication of requests:
session.auth = ("user", "password")

# Headers sent with every request, for example, an API key:
session.headers["X-API-Key"] = "my-secret-key"

transport = aas_client_requests_transport.RequestsTransport(
    session, timeout=10.0
)

server = aas_client_http.Server(
    transport=transport, base_url="http://localhost:5005"
)

The certificate of the server is checked against session.verify, and a client certificate for mutual TLS is given in session.cert. For OAuth 2 and OpenID Connect, use the sessions of authlib or requests-oauthlib, which are both sub-classes of requests.Session, and refresh the tokens for you.

The client never caches the credentials and never retries: every request, and every page of a listing, goes through the transport anew.

Write Your Own Transport

A transport is any object with the method send of aas_client3_2.http.Transport. It gives the response as a context manager, so that the body can be streamed, and the connection is released at the end of the context.

The simplest transports wrap another one. For example, a transport which logs the requests:

class LoggingTransport:
    def __init__(self, inner: aas_client_http.Transport) -> None:
        self.inner = inner

    @contextlib.contextmanager
    def send(
        self, request: aas_client_http.Request
    ) -> Iterator[aas_client_http.StreamedResponse]:
        with self.inner.send(request) as response:
            print(
                f"{request.method} {request.url} -> {response.status_code}"
            )
            yield response


logged_server = aas_client_http.Server(
    transport=LoggingTransport(transport),
    base_url="http://localhost:5005",
)

page = aas_client_submodel_repository.get_all_submodels(
    logged_server, limit=1
)
# Prints: GET http://localhost:5005/submodels?limit=1 -> 200

To use another HTTP library, such as httpx, implement send with it; see the source of aas_client3_2.requests_transport for a complete example.

Refresh a Token

If you obtain the tokens yourself, a wrapping transport can ask for the current token on every request, and retry once with a fresh token if the server responds with 401. The bodies of the requests can be iterated anew, so the retry also works for the uploads of large files:

class TokenProvider:
    """Give the current token, e.g., from your identity provider."""

    def token(self) -> str:
        return "my-token"

    def invalidate(self) -> None:
        """Forget the token, so that the next call obtains a new one."""


def with_token(
    request: aas_client_http.Request, token: str
) -> aas_client_http.Request:
    headers = dict(request.headers)
    headers["Authorization"] = f"Bearer {token}"
    return dataclasses.replace(request, headers=headers)


class BearerTransport:
    def __init__(
        self,
        inner: aas_client_http.Transport,
        provider: TokenProvider,
    ) -> None:
        self.inner = inner
        self.provider = provider

    @contextlib.contextmanager
    def send(
        self, request: aas_client_http.Request
    ) -> Iterator[aas_client_http.StreamedResponse]:
        with self.inner.send(
            with_token(request, self.provider.token())
        ) as response:
            if response.status_code != 401:
                yield response
                return

        # The first connection is released before the retry.
        self.provider.invalidate()
        with self.inner.send(
            with_token(request, self.provider.token())
        ) as response:
            yield response


authenticated_server = aas_client_http.Server(
    transport=BearerTransport(transport, TokenProvider()),
    base_url="http://localhost:5005",
)

If the token is still refused after the refresh, the client raises Unauthorized with the response, including its header WWW-Authenticate.