Build · Reference

Python client

The same client in Python, using the requests package.

Updated 2 December 2026

About this client

The Python equivalent: one file, one dependency (requests). It does everything the TypeScript client does, and the tests run it against a stand-in for the API with the real requests library.

bash
pip install requests

Using it

python
from colossium import Colossium, ColossiumError

c = Colossium()                          # reads COLOSSIUM_API_TOKEN
print(c.verify()["scopes"])

for project in c.iterate("/projects"):
    print(project["slug"])

try:
    request, replayed = c.create_request(
        "storage.create",
        {"name": "assets", "region": "eu"},
        project_id="3f2b8c1e-5d4a-4e7b-9c1d-2a6f8e0b4d37",
        idempotency_key="release-2026-12-02-assets",   # the intent, never personal data
    )
    done = c.wait_for(request["id"])
    print(done["state"], done["resource_id"])
except ColossiumError as e:
    print(e.code, e.status, e.request_id)             # never the token

The source

python
"""A small client for the Colossium API. Copy this file into your project. It needs the requests package.

It reads the token from COLOSSIUM_API_TOKEN, retries 429 and 5xx responses with backoff and jitter, retries a POST only when it carries
an Idempotency-Key, never writes the token to a log or an error, and walks every page of a list for you.
"""
import os
import random
import re
import time
import uuid

import requests

TOKEN_SHAPE = re.compile(r"^clsm_[0-9A-Za-z]{46}$")
TERMINAL = {"succeeded", "failed", "cancelled"}
TRANSIENT = {429, 500, 502, 503, 504}


class ColossiumError(Exception):
    """Every error response arrives as this. Log request_id and code. Never log the token."""

    def __init__(self, status, code, message, request_id=None, doc_url=None, details=None):
        super().__init__(message)
        self.status, self.code, self.request_id, self.doc_url, self.details = status, code, request_id, doc_url, details


def delay_for(attempt, retry_after=None):
    """Exponential backoff with full jitter, capped at 30 seconds. Retry-After wins, capped at 60 seconds."""
    if retry_after is not None and retry_after.isdigit():
        return min(int(retry_after), 60)
    return random.random() * min(30.0, 0.5 * 2 ** attempt)


class Colossium:
    def __init__(self, token=None, base_url="https://api.colossium.cloud/v1", timeout=30, max_retries=4, session=None):
        token = token or os.environ.get("COLOSSIUM_API_TOKEN")
        if not token:
            raise ValueError("Set COLOSSIUM_API_TOKEN, or pass token=.")
        if not TOKEN_SHAPE.match(token):
            raise ValueError("That does not look like a Colossium token. It should start with clsm_ and be 51 characters long.")
        self._token = token
        self.base_url = base_url.rstrip("/")
        self.timeout, self.max_retries = timeout, max_retries
        self._http = session or requests.Session()
        self.last_rate = None

    def __repr__(self):  # the token never appears when the client is printed
        return f"Colossium(base_url={self.base_url!r})"

    def request(self, method, path, params=None, json=None, idempotency_key=None):
        headers = {"Authorization": f"Bearer {self._token}", "Accept": "application/json"}
        if idempotency_key:
            headers["Idempotency-Key"] = idempotency_key
        retryable = method == "GET" or idempotency_key is not None
        attempt = 0
        while True:
            try:
                res = self._http.request(method, self.base_url + path, params=params, json=json, headers=headers, timeout=self.timeout)
            except requests.RequestException:
                if not (retryable and attempt < self.max_retries):
                    raise ColossiumError(0, "network_error", "The request could not be sent.")
                time.sleep(delay_for(attempt))
                attempt += 1
                continue
            if "X-RateLimit-Limit" in res.headers:
                self.last_rate = {k: int(res.headers[h]) for k, h in (("limit", "X-RateLimit-Limit"), ("remaining", "X-RateLimit-Remaining"), ("reset", "X-RateLimit-Reset"))}
            if res.ok:
                return res.json(), res.headers.get("Idempotent-Replayed") == "true"
            if res.status_code in TRANSIENT and retryable and attempt < self.max_retries:
                time.sleep(delay_for(attempt, res.headers.get("Retry-After")))
                attempt += 1
                continue
            try:
                e = res.json().get("error", {})
            except ValueError:
                e = {}
            raise ColossiumError(res.status_code, e.get("code", "unknown_error"), e.get("message", f"The API answered {res.status_code}."),
                                 e.get("request_id") or res.headers.get("X-Request-Id"), e.get("doc_url"), e.get("details"))

    def iterate(self, path, **params):
        """Every item of a list, one page at a time."""
        cursor = None
        while True:
            page, _ = self.request("GET", path, params={"limit": 100, **params, **({"cursor": cursor} if cursor else {})})
            yield from page["data"]
            cursor = page["next_cursor"]
            if not cursor:
                return

    def verify(self):
        return self.request("GET", "/token/verify")[0]

    def create_project(self, name, slug, description=""):
        return self.request("POST", "/projects", json={"name": name, "slug": slug, "description": description})[0]

    def create_request(self, kind, input, project_id=None, idempotency_key=None):
        """Ask for something. Pass the same idempotency_key to retry safely. Derive it from the intent, never from personal data."""
        key = idempotency_key or str(uuid.uuid4())
        body, replayed = self.request("POST", "/requests", json={"kind": kind, "project_id": project_id, "input": input}, idempotency_key=key)
        return body, replayed

    def wait_for(self, request_id, timeout=900, interval=5):
        deadline = time.time() + timeout
        while True:
            r, _ = self.request("GET", f"/requests/{request_id}")
            if r["state"] in TERMINAL:
                return r
            if time.time() >= deadline:
                raise ColossiumError(0, "wait_timeout", f"The request is still {r['state'].replace('_', ' ')} after waiting.")
            time.sleep(max(interval, 15) if self.last_rate and self.last_rate["remaining"] < 5 else interval)

This page as MarkdownReport a problem with this pageOlympus Group Holdings, Inc.