Skip to main content

ratum — Python-SDK

Python-Client für die ratum Integrations-API (ADR-016). Sync und async, Python ≥ 3.11, httpx.

  • Low-Level-Client ratum.generated: generiert mit openapi-python-client aus der eingecheckten openapi.json. Nicht von Hand ändern.
  • Komfortschicht Ratum / AsyncRatum: upload_document, create_and_send (setzt Idempotency-Key automatisch), wait_for_completion, dazu verify_webhook_signature, Retries bei 429/5xx mit Retry-After und typisierte Exceptions aus dem RFC-9457-code.

Status 0.1.0, noch nicht auf PyPI. Installation aus dem Repo: pip install "ratum @ git+https://github.com/talent-factory/ratum#subdirectory=sdk/python"

Quickstart

from ratum import Ratum

with Ratum("ratum_test_…") as client:  # base_url=… für Staging/lokal
    doc = client.create_and_send(
        "vertrag.pdf",
        signers=[
            {
                "email": "anna@example.ch",
                "fields": [
                    {
                        "field_type": "signature",
                        "page": 1,
                        "x": 60,
                        "y": 700,
                        "width": 200,
                        "height": 50,
                        "page_width": 595,
                        "page_height": 842,
                    }
                ],
            }
        ],
    )
    done = client.wait_for_completion(doc.id, timeout=3600)
    print(done.status, done.failure_code)

Async: AsyncRatum mit denselben Methoden (async with, await). Lauffähige Beispiele: examples/quickstart.py, examples/quickstart_async.py.

create_and_send lädt die Datei presigned hoch, ruft /complete auf und gibt den aktuellen Dokumentstand zurück. Versendet wird serverseitig, sobald Scan und ggf. DOCX-Konvertierung durch sind. Wer den Aufruf nach einem Absturz ohne Doppelversand wiederholen will, übergibt einen eigenen, stabilen idempotency_key (z. B. die eigene Auftrags-ID). Das schützt, solange das Backend die Antwort speichert (24 h); nach Ablauf der Upload-URL (derzeit 15 min) scheitert die Wiederholung aber mit UploadError, obwohl das Dokument womöglich schon versendet ist — dann zuerst get_document prüfen.

wait_for_completion gibt das Dokument im Endzustand zurück (signed, declined, failed, archived), auch bei failed; der Grund steht in failure_code. archived sagt nichts über den Ausgang (auch Entwürfe lassen sich archivieren) — dafür die Signer-Status prüfen. Läuft die Frist ab, wirft es WaitTimeoutError mit dem letzten Stand in .document. Für lange Signierfristen sind Webhooks die bessere Wahl.

Anker statt Koordinaten, eigene Zustellung

doc = client.create_and_send(
    "vertrag.docx",  # enthält z. B. {{ratum:signature:1}} und {{ratum:date:1}}
    signers=[{"email": "anna@example.ch"}],  # Felder kommen aus den Ankern
    anchors=True,  # oder {"sizes": {"signature": {"width": 200, "height": 60}}}
    delivery="none",  # ratum mailt dem Signer nicht
)
# Nach Webhook `signer.activated` (oder per Polling) den Link holen und selbst zustellen:
link = client.get_signing_link(doc.id, doc.signers[0].id)

Fehlt ein Anker, endet das Dokument mit status=failed und failure_code=anchor_not_found. Jeder get_signing_link-Aufruf entwertet den vorherigen Link. Das versiegelte PDF nach signed: client.download_sealed_document(doc.id) (kurz nach signed evtl. noch 404).

Webhooks

Endpoints verwalten (Scope webhooks:manage, max. 3):

endpoint = client.create_webhook("https://example.ch/ratum-hook", events=["document.completed"])
secret = endpoint.secret  # nur in dieser Antwort — sicher ablegen
client.send_test_webhook(endpoint.id)  # webhook.ping
client.list_webhook_deliveries(endpoint.id)  # Zustell-Log
client.rotate_webhook_secret(endpoint.id)  # neues Secret, wirkt sofort

Empfangen und prüfen:

from ratum import SIGNATURE_HEADER, WebhookSignatureError, verify_webhook_signature


def handle(request):  # Django; Flask: request.get_data(), FastAPI: await request.body()
    try:
        event = verify_webhook_signature(
            request.body,  # unveränderter Raw-Body
            request.headers.get(SIGNATURE_HEADER),
            secret="…",  # Secret des Endpoints
        )
    except WebhookSignatureError:
        return 400
    ...  # event["id"] zum Deduplizieren, event["type"], event["data"]

Header Ratum-Signature: t=<unix>,v1=<hex>, HMAC-SHA256 über "<t>.<body>"; Zeitstempel ausserhalb ±5 min werden abgelehnt (tolerance= anpassbar). Ein leeres secret ist ein Konfigurationsfehler (ValueError), nicht „alles erlaubt".

Fehler und Retries

Exception code
InvalidRequestError bad_request, validation_error, method_not_allowed, payload_too_large, idempotency_key_required, idempotency_key_invalid, webhook_url_rejected
AuthenticationError unauthenticated
PermissionDeniedError plan_required, insufficient_scope, forbidden
NotFoundError not_found
ConflictError conflict, not_ready, idempotency_key_reused (HTTP 422), idempotency_key_in_use
DocumentProcessingError scan_infected, scan_failed, conversion_failed, anchor_not_found, anchor_scan_failed
QuotaExceededError quota_exceeded (Freemium-Monatslimit, 402)
RateLimitError rate_limited (Rate-/Tageslimit, Cooldown; 429)
ServerError internal_error, jeder 5xx

Alle oben erben von APIError (.status, .code, .detail, .problem, .errors, .headers, .retry_after, .body_text). Unbekannte Codes einer neueren API werden über den HTTP-Status zugeordnet. Antworten ohne code (z. B. HTML einer Bot-Abwehr oder eines Proxys) werden zu einem generischen APIError mit dem Anfang des Bodys in der Meldung — bzw. zu ServerError (5xx) und RateLimitError (429).

Ausserdem, direkt unter RatumError:

Exception Wann
APIConnectionError / APITimeoutError Netzwerkfehler bzw. Timeout, auch nach den Retries (Ursache in __cause__)
UploadError presigned Upload in den Storage fehlgeschlagen (inkl. Redirect)
WaitTimeoutError wait_for_completion abgelaufen (.document)
WebhookSignatureError Webhook-Signatur ungültig

Eine Antwort, die das SDK nicht lesen kann (z. B. ein neuer status-Wert einer neueren API), wird zu RatumError mit Hinweis auf ein SDK-Update. except RatumError fängt damit alles.

Retries (Default max_retries=2):

  • 429 immer;
  • 500/502/503/504 und Netzwerkfehler nur bei GET/HEAD/PUT/DELETE/OPTIONS oder mit Idempotency-Key, damit nichts doppelt ausgeführt wird;
  • 409 idempotency_key_in_use mit Retry-After (erster Versuch läuft serverseitig noch).

Gewartet wird Retry-After (Sekunden oder HTTP-Datum), sonst exponentiell ab 0,5 s mit Jitter. Verlangt der Server mehr als 30 s, wartet das SDK nicht, sondern wirft sofort (retry_after am Fehler). Gilt auch für den Low-Level-Client unter client.api — dort aber nur die zum Client passenden Funktionen nutzen (Ratum.api → sync…, AsyncRatum.api → asyncio…); sie werfen ebenfalls statt ProblemDetails zurückzugeben.

Proxy: HTTPS_PROXY/HTTP_PROXY/ALL_PROXY/NO_PROXY aus der Umgebung wie bei httpx. Ein eigener transport= ersetzt das.

Entwicklung

just sdk-py-generate   # nach jeder Änderung an openapi.json (`just be-openapi`)
just sdk-py-check      # Drift-Check, ruff, mypy, pytest + Coverage ≥ 90 % (Komfortschicht)

Generator (openapi-python-client) und ruff sind exakt gepinnt, damit die Generierung reproduzierbar ist; CI vergleicht den eingecheckten Code mit einer frischen Generierung.

Metadata

Release files for ratum 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for ratum 0.1.0
File Size Uploaded Provenance Actions
ratum-0.1.0.tar.gz 136.6 kB With provenance Details for ratum-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for ratum 0.1.0
File Interpreter ABI Platform Actions
ratum-0.1.0-py3-none-any.whl Python 3 none any Details for ratum-0.1.0-py3-none-any.whl

Total release size: 262.3 kB

Release files / ratum-0.1.0.tar.gz

Download URL ratum-0.1.0.tar.gz
Size 136.6 kB
Tags Source
SHA-256 checksum
How to use checksums
e59461f7377684439398b6f0b1086490c5a9a51503194d4780c8aea954b6dff5
BLAKE2b-256 checksum
How to use checksums
f12bbf6a8e80a0856590cd800d4f71ccc3abd73c4cd87082b84f95ffb553ba1d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 16, 2026.

Transparency log

Release files / ratum-0.1.0-py3-none-any.whl

Download URL ratum-0.1.0-py3-none-any.whl
Size 125.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
33df2d60f796bd14f26811308153716955360ed6eb456749253854bcb8903537
BLAKE2b-256 checksum
How to use checksums
5a5a1fb534afb5706fa4a8a42f487207f3dc9239031dc2795d4ef632d3b16be6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 16, 2026.

Transparency log

Security for ratum 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for ratum-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 16, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page