Skip to content
Menu · Python

SDKs

Python

Install the composa-labs package, set up the client, and print documents, batches and webhooks from Python.

The official Python library for the Composa API. It is published on PyPI as composa-labs and imported as composa. Source: github.com/Composa-Labs/composa-python.

Install

bash
pip install composa-labs

Python 3.10 or later. Its only dependency is httpx.

Setup

Make an API key on the API keys page of the app (see Authentication), then:

bash
export COMPOSA_API_KEY="cmp_live_..."
python
from composa import Composa​composa = Composa()  # reads COMPOSA_API_KEY; or Composa("cmp_live_...")

A long-lived process (a web server, a worker) keeps one client for its whole life. A script can close it when done, with composa.close() or a with block:

python
from composa import Composa​with Composa() as composa:    template = composa.templates.get("85416813-8d99-46e8-be2b-1d61cee5db38")

Every method below raises a ComposaError when a call fails. See Errors.

documents.create

Prints one document with POST /v1/run.

python
from pathlib import Path​pdf = composa.documents.create(    template_id="85416813-8d99-46e8-be2b-1d61cee5db38",    data={"full_name": "Ada Lovelace", "total": 1250.5},)Path(pdf.filename or "document.pdf").write_bytes(pdf.content)

data holds your template's fields by their own names. The other options are format ("pdf", "png", "jpg", "webp", "svg"), quality, scale, width, pages, language and version.

Pass output="url" for a link instead of the file:

python
link = composa.documents.create(    template_id="85416813-8d99-46e8-be2b-1d61cee5db38",    data={"full_name": "Ada Lovelace"},    output="url",)print(link.url, link.url_expires_in, link.pages)

A link works for an hour: download the file rather than storing the link.

templates.get

Reads a template's fields with GET /v1/contract.

python
template = composa.templates.get("85416813-8d99-46e8-be2b-1d61cee5db38")print(f"version {template.version}")for field in template.fields:    print(field.name, field.kind, field.if_no_value, field.columns or "")

Pass version=3 to read a version other than the active one.

batches.create

Starts a batch of up to 50,000 documents.

python
batch = composa.batches.create(    template_id="85416813-8d99-46e8-be2b-1d61cee5db38",    items=[        {"name": "ada", "data": {"full_name": "Ada Lovelace"}},        {"name": "grace", "data": {"full_name": "Grace Hopper"}},    ],)

A batch of any size is this one call: the SDK sends a large one (more than 4 MB of JSON, up to 64 MB) as a file by itself. Pass data alone, in place of items, for a batch of one. Pictures go in data as https:// addresses, not as base64.

batches.wait_for

Polls until the batch has ended (completed, failed, expired, canceled) or paused, and hands it back.

python
done = composa.batches.wait_for(batch.batch_id)print(done.status, done.success_count, done.error_count)for item in done.items:    print(item.index, item.name, item.output_url or item.error)

It polls every 2 seconds for 10 minutes at most; change that with interval and timeout, in seconds.

batches.get

Reads a batch once. Items come up to 1,000 at a time:

python
page = composa.batches.get(batch.batch_id, offset=done.next_offset)

batches.cancel

python
composa.batches.cancel(batch.batch_id)

webhooks.verify

Checks a webhook's signature against the raw body and returns the event. It needs no API key: set COMPOSA_WEBHOOK_SECRET to the endpoint's signing secret, or pass secret=.

python
from fastapi import FastAPI, HTTPException, Request​from composa import WebhookVerificationError, webhooks​app = FastAPI()​​@app.post("/composa/webhooks", status_code=204)async def composa_webhook(request: Request) -> None:    try:        event = webhooks.verify(await request.body(), request.headers.get("composa-signature"))    except WebhookVerificationError as error:        raise HTTPException(status_code=400, detail=error.message) from error​    if event.type == "batch.completed":        print("batch done:", event.data["batch_id"], event.data["status_url"])

Pass the body exactly as it arrived, never one already parsed as JSON. event.data holds each event's fields under the API's own names.

Errors

python
from composa import Composa, ComposaError​composa = Composa()​try:    composa.documents.create(        template_id="85416813-8d99-46e8-be2b-1d61cee5db38",        data={"total": "not a number"},    )except ComposaError as error:    print(error.code, error.status_code, error.message)    for problem in error.problems:        print(" ", problem.field, problem.reason)    if error.retry_after is not None:        print(f"try again in {error.retry_after} s")
  • code is the API's own (no_usable_value, rate_limited, credits_exhausted, …) or, when it sent none, one derived from the status (unauthorized, not_found, conflict, …).
  • connection_error, timeout and invalid_response mean no usable answer came back.
  • request_id is the reference to quote to support.

The SDK never retries a call by itself: each print counts its pages again.

Options

python
import httpx​from composa import Composa​composa = Composa(    "cmp_live_...",    base_url="https://api.composa.ai",  # or COMPOSA_BASE_URL    timeout=120.0,  # seconds a call may take; None for no limit    http_client=httpx.Client(proxy="http://localhost:8080"),)