Skip to content

API integration recipes

Each recipe assumes the catalog profile. Paths, response fields and accepted status codes come from the example provider. Check those details against your API before using a recipe with a real service.

Suppose GET /products returns {"items":[{"id":42}],"next_cursor":"next-2"} and the last page returns null for next_cursor. Pass the cursor through params so the client encodes it. Keep the path bound to the catalog and stop on a repeated cursor or an excessive number of pages.

from orionis.http.client.contracts import IHttpManager
async def product_ids(http: IHttpManager, max_pages: int = 20) -> list[int]:
catalog = http.client("catalog").acceptJson()
ids = []
params = {}
seen = set()
for _ in range(max_pages):
result = await catalog.get("/products", params=params)
result.throw()
if not result.ok():
raise ValueError("Expected a page with status 200")
data = result.json()
ids.extend(item["id"] for item in data["items"])
cursor = data["next_cursor"]
if cursor is None:
return ids
if not isinstance(cursor, str) or not cursor or cursor in seen:
raise ValueError("Invalid or repeated catalog cursor")
seen.add(cursor)
params = {"cursor": cursor}
raise ValueError("Catalog page limit reached")

For a two-page test, register GET https://catalog.example.com/products and GET https://catalog.example.com/products?cursor=next-2 as separate fixtures. If the second page contains product 43 and next_cursor is null, the function returns [42, 43]. Testing exact URLs

Reuse a response when the provider returns 304

Section titled “Reuse a response when the provider returns 304”

If the provider supports ETag, keep the representation and its tag together. On the first call pass b"" and None. On later calls send the previous tag exactly as received, including quotes. A 304 asks you to keep the saved bytes. It has no replacement document to decode.

from orionis.http.client.contracts import IHttpManager
async def refresh_product(
http: IHttpManager, saved: bytes, etag: str | None
) -> tuple[bytes, str | None]:
catalog = http.client("catalog")
if etag is not None:
catalog = catalog.withHeaders({"If-None-Match": etag})
result = await catalog.get("/products/42")
if result.status() == 304 and etag is not None:
return saved, etag
result.throw()
if not result.ok():
raise ValueError("Expected a full product representation")
return result.body(), result.header("ETag")

Your application owns this cache. Keep entries separate by product and by any credentials or representation headers that change the result. A different product or account starts with a fresh entry.

Suppose the provider accepts a PDF directly at PUT /products/42/label. Read at most one byte beyond the application’s 128 KiB limit before sending. The framework also applies the profile’s request budget. Put blocking file reads in a thread so other tasks on the loop can run.

import asyncio
from pathlib import Path
from orionis.http.client.contracts import IHttpManager
def read_label(path: Path) -> bytes:
limit = 128 * 1024
with path.open("rb") as stream:
body = stream.read(limit + 1)
if len(body) > limit:
raise ValueError("Label exceeds 128 KiB")
return body
async def upload_label(http: IHttpManager, path: Path) -> int:
body = await asyncio.to_thread(read_label, path)
catalog = http.client("catalog").withHeaders({"Content-Type": "application/pdf"})
result = await catalog.put("/products/42/label", content=body)
result.throw()
if result.status() not in (200, 201, 204):
raise ValueError("Unexpected upload status")
return result.status()

For a small download, use await http.client("catalog").get("/products/42/label"), check the expected 200 and media type, then save result.body(). The response must fit within max_response_bytes. In v1.10.0 bodies are buffered, and the public API has no multipart files= argument or streaming download iterator. Raw content= is suitable when the provider accepts the file itself. Body formats

Suppose POST /exports creates one export and returns 201 with {"id":"exp-7"}. This provider documents an Idempotency-Key header. Create and persist an operation key when the business action begins. Give the same key and payload to every delivery of that action. The provider must actually implement deduplication for this to work.

from orionis.http.client.contracts import IHttpManager
class CatalogRateLimit(Exception):
def __init__(self, retry_after: str | None) -> None:
super().__init__("Catalog rate limit reached")
self.retry_after = retry_after
async def create_export(http: IHttpManager, operation_key: str) -> str:
catalog = http.client("catalog").withHeaders({"Idempotency-Key": operation_key})
result = await catalog.post("/exports", json={"product_id": 42})
if result.status() == 429:
raise CatalogRateLimit(result.header("Retry-After"))
result.throw()
if result.status() != 201:
raise ValueError("Expected export creation")
export_id = result.json("id", default=None)
if not isinstance(export_id, str):
raise ValueError("Expected an export ID")
return export_id

The caller can catch CatalogRateLimit and reschedule the job. Retry-After may contain seconds, an HTTP date or no value. Interpret it according to the provider’s contract and apply a bounded retry policy. Each Orionis send makes one attempt. A timeout after sending a write leaves its remote outcome unknown. Look up the operation by key or reconcile its state before submitting another write. Timeout phases · Queue attempts