s365b.graph.client ================== .. py:module:: s365b.graph.client .. autoapi-nested-parse:: Async Microsoft Graph client. Behaviour every module gets for free: * **Throttling:** 429 and 503/504 responses are retried after the ``Retry-After`` delay (or exponential backoff with jitter). While one request is throttled, all requests through the same client pause, which is what Graph expects of a well-behaved client. * **Concurrency limit:** at most ``max_concurrency`` requests in flight. * **Auth:** a 401 triggers one token refresh and retry. * **Paging:** :meth:`GraphClient.paginate` follows ``@odata.nextLink``. * **Delta queries:** :meth:`GraphClient.delta` returns items plus the new ``@odata.deltaLink``; an expired link raises :class:`DeltaExpiredError` so the module can do a full resync. * **Batching:** :meth:`GraphClient.batch` sends up to 20 requests per call. * **Streaming:** :meth:`GraphClient.stream` downloads content without holding it in memory. Attributes ---------- .. autoapisummary:: s365b.graph.client.GRAPH_V1 s365b.graph.client.RETRY_STATUSES s365b.graph.client.RETRY_STATUSES_UNSAFE s365b.graph.client.NOT_SENT s365b.graph.client.BATCH_LIMIT s365b.graph.client.log Exceptions ---------- .. autoapisummary:: s365b.graph.client.GraphError s365b.graph.client.DeltaExpiredError Classes ------- .. autoapisummary:: s365b.graph.client.DeltaResult s365b.graph.client.BatchRequest s365b.graph.client.BatchResponse s365b.graph.client.GraphClient Module Contents --------------- .. py:data:: GRAPH_V1 :value: 'https://graph.microsoft.com/v1.0' .. py:data:: RETRY_STATUSES .. py:data:: RETRY_STATUSES_UNSAFE .. py:data:: NOT_SENT .. py:data:: BATCH_LIMIT :value: 20 .. py:data:: log .. py:exception:: GraphError(status: int, code: str, message: str, request_id: str | None = None) Bases: :py:obj:`Exception` An error response from Microsoft Graph. :ivar status: HTTP status code. :ivar code: Graph error code, e.g. ``"ErrorItemNotFound"``. :ivar message: Graph error message. :ivar request_id: ``request-id`` header, useful for Microsoft support. .. py:attribute:: status .. py:attribute:: code .. py:attribute:: message .. py:attribute:: request_id :value: None .. py:method:: from_response(resp: httpx.Response) -> GraphError :classmethod: Build an error from an HTTP response. :param resp: The failed response. :returns: The error (a :class:`DeltaExpiredError` for expired delta links). .. py:exception:: DeltaExpiredError(status: int, code: str, message: str, request_id: str | None = None) Bases: :py:obj:`GraphError` The delta link is no longer valid; a full resync is needed. .. py:class:: DeltaResult Result of a delta query. :ivar items: Changed items. Deleted items carry an ``@removed`` key. :ivar delta_link: Link to pass next time to get only later changes (last page only). :ivar next_link: Link to the next page; saving it lets an interrupted first sync resume where it stopped. .. py:attribute:: items :type: list[dict[str, Any]] :value: [] .. py:attribute:: delta_link :type: str | None :value: None .. py:attribute:: next_link :type: str | None :value: None .. py:class:: BatchRequest One request inside a JSON batch. :ivar id: Caller-chosen ID to match responses. :ivar method: HTTP method. :ivar url: URL relative to the API version, e.g. ``/users/{id}``. :ivar body: Optional JSON body. .. py:attribute:: id :type: str .. py:attribute:: method :type: str .. py:attribute:: url :type: str .. py:attribute:: body :type: dict[str, Any] | None :value: None .. py:class:: BatchResponse One response from a JSON batch. :ivar id: Matching :attr:`BatchRequest.id`. :ivar status: HTTP status of this sub-request. :ivar body: Parsed body (may be empty). .. py:attribute:: id :type: str .. py:attribute:: status :type: int .. py:attribute:: body :type: dict[str, Any] .. py:class:: GraphClient(token_provider: s365b.graph.auth.TokenProvider, *, base_url: str = GRAPH_V1, max_concurrency: int = 4, max_retries: int = 8, max_backoff: float = 120.0, http: httpx.AsyncClient | None = None) Async client for Microsoft Graph. :param token_provider: Supplies access tokens. :param base_url: API root, ``https://graph.microsoft.com/v1.0`` by default. :param max_concurrency: Maximum parallel requests. :param max_retries: Retries per request for throttling and server errors. :param max_backoff: Upper bound in seconds for any single wait. :param http: Optional pre-built ``httpx.AsyncClient`` (tests). .. py:attribute:: base_url :value: '' .. py:method:: aclose() -> None :async: Close the underlying HTTP connections. .. py:method:: request(method: str, url: str, *, json: Any = None, content: bytes | None = None, params: dict[str, Any] | None = None, headers: dict[str, str] | None = None, authenticate: bool = True, idempotent: bool = True) -> httpx.Response :async: Send a request and return the (fully read) response. :param method: HTTP method. :param url: Absolute URL or path relative to :attr:`base_url`. :param json: JSON body. :param content: Raw body (e.g. a piece of a file upload), instead of ``json``. :param params: Query parameters. :param headers: Extra headers (e.g. ``ConsistencyLevel: eventual``). :param authenticate: False to send no access token (pre-authenticated URLs). :param idempotent: False for a request that creates something; it is not retried when it may already have been carried out. :returns: The successful response. :raises GraphError: For error responses after retries. .. py:method:: get_json(url: str, *, params: dict[str, Any] | None = None, headers: dict[str, str] | None = None) -> dict[str, Any] :async: GET a URL and return the JSON body. :param url: Absolute URL or path. :param params: Query parameters. :param headers: Extra headers, e.g. ``Prefer: IdType="ImmutableId"``. :returns: The parsed body. .. py:method:: paginate(url: str, *, params: dict[str, Any] | None = None, headers: dict[str, str] | None = None) -> collections.abc.AsyncIterator[dict[str, Any]] :async: Yield every item of a collection, following ``@odata.nextLink``. :param url: Collection URL or path. :param params: Query parameters for the first page. :param headers: Extra headers for every page. :Yields: Items from the ``value`` arrays. .. py:method:: delta(url: str, *, delta_link: str | None = None, params: dict[str, Any] | None = None, headers: dict[str, str] | None = None) -> collections.abc.AsyncIterator[DeltaResult] :async: Run a delta query page by page. Each yielded :class:`DeltaResult` holds one page of items; the last one also carries ``delta_link``. Modules can checkpoint after each page. :param url: Delta URL for the first full sync, e.g. ``/users/{id}/mailFolders/{fid}/messages/delta``. :param delta_link: Saved delta link from the previous run; when given, ``url`` and ``params`` are ignored. :param params: Query parameters for the initial request. :param headers: Extra headers for every page (e.g. ``Prefer`` for immutable IDs or page size). :Yields: Pages of changes. :raises DeltaExpiredError: If ``delta_link`` has expired (HTTP 410). .. py:method:: batch(requests: list[BatchRequest]) -> list[BatchResponse] :async: Send requests as JSON batches of up to 20, retrying throttled ones. :param requests: Requests with unique IDs. :returns: Responses in the same order as ``requests``. .. py:method:: stream(url: str, *, chunk_size: int = 1024 * 1024, headers: dict[str, str] | None = None) -> collections.abc.AsyncIterator[bytes] :async: Download content as a stream of byte chunks. :param url: Content URL, e.g. ``/users/{id}/messages/{mid}/$value``. :param chunk_size: Preferred piece size. :param headers: Extra headers. :Yields: Pieces of the body.