Python
Render documents, wait for async renders, verify webhooks and create embedded editor sessions with the official Python SDK, sync or async.
druckling is the official Python client for the Druckling API. It has a synchronous Druckling client and an asynchronous AsyncDruckling client with the same methods, typed dataclass models and typed exceptions. Its only dependency is httpx.
Install
Requirements:
- Python 3.9 or later.
httpx0.23 or later (below 1.0), installed automatically.
The package isn't on PyPI yet. Install it from the Druckling source repository:
pip install "git+https://github.com/vulpery/druckling.git#subdirectory=src/integrations/sdk-python"In a requirements.txt or pyproject.toml dependency list, use a direct reference:
druckling @ git+https://github.com/vulpery/druckling.git#subdirectory=src/integrations/sdk-pythonThen create a key under Developers › API keys and export it:
export DRUCKLING_API_KEY=dr_test_...Configuration
from druckling import Druckling
client = Druckling(
api_key="dr_test_...",
base_url="https://druckling-nine.vercel.app",
timeout=60.0,
max_retries=2,
)| Option | Default | Notes |
|---|---|---|
api_key | DRUCKLING_API_KEY | An dr_test_… or dr_live_… key, sent as Authorization: Bearer …. The only positional argument; the others are keyword-only. Without a key the constructor raises DrucklingError. |
base_url | DRUCKLING_BASE_URL, then https://druckling-nine.vercel.app | With or without a trailing /v1. |
timeout | 60.0 | Seconds per HTTP attempt, see Retries and timeouts. |
max_retries | 2 | Retries after the first attempt. 0 turns retries off. |
http_client | a new httpx.Client | Your own httpx.Client (httpx.AsyncClient for AsyncDruckling), for proxies, custom TLS or transports. |
default_headers | none | Extra headers on every API request. |
client.with_options(timeout=..., max_retries=...)returns a copy with other settings that shares the connection pool.- Use the client as a context manager (
with Druckling() as client:) or callclient.close()to release its connections. The SDK only closes HTTP clients it created itself. client.modeis"test"fordr_test_…keys,"live"fordr_live_…keys, and"unknown"otherwise.client.base_urlis the origin requests go to, without/v1.
Custom HTTP client
Pass an httpx client to control proxies, TLS or connection limits:
import httpx
from druckling import Druckling
client = Druckling(http_client=httpx.Client(proxy="http://proxy.internal:3128"))The SDK sets its own timeout on every request, so configure timeouts with the SDK's timeout option rather than on the httpx client.
Async client
AsyncDruckling takes the same options (with an httpx.AsyncClient as http_client) and has the same resources and methods; you await them:
import asyncio
from druckling import AsyncDruckling
async def main() -> None:
async with AsyncDruckling() as client:
template = await client.templates.get("invoice-standard") # reading templates needs a Full access key
document = await client.documents.create(template=template.slug, data=template.sample_data)
await client.documents.download_to(document, "sample.pdf")
asyncio.run(main())Close it with async with or await client.close(). The examples below use the sync client; with AsyncDruckling, add await (and async for when iterating pages).
Render a document
documents.create validates data against the template's JSON Schema and renders the document. By default it waits for the file and returns a rendered document:
from druckling import Druckling
client = Druckling()
invoice = {
"invoice": {"number": "INV-2041", "due_date": "2026-11-22"},
"customer": {"name": "Northwind Ltd.", "address": "12 Pier St, Leeds"},
"line_items": [
{"description": "Brand identity, phase 2", "qty": 1, "rate": 4800, "amount": 4800},
{"description": "Design system audit", "qty": 12, "rate": 180, "amount": 2160},
],
"totals": {"subtotal": 6960, "tax": 556.8, "amount": 7516.8},
"payment": {"url": "https://pay.example.com/INV-2041"},
}
document = client.documents.create(template="invoice-standard", filename="INV-2041.pdf", data=invoice)
print(document.id, document.status, document.pages) # pdf_… rendered 1
client.documents.download_to(document, "INV-2041.pdf")All arguments are keyword-only: template (slug), data, and optionally version (a published version number, default "latest"), filename, async_, language and format.
data is sent as JSON: datetime.date and datetime.datetime values become ISO 8601 strings, Decimal values become numbers. It must match the template's schema; client.templates.get("invoice-standard").sample_data is a payload that renders. See Variables.
The returned Document has the API's fields as snake_case attributes (size_bytes, content_type, test_mode, …), with created_at and expires_at as timezone-aware datetime objects. document.raw holds the response exactly as the API returned it, including fields the model doesn't declare yet, such as image and batch. See Retrieve a document for every field.
Render asynchronously and wait
Pass async_=True (async is a reserved word in Python) to queue the render. create returns right away with status queued, and the file is rendered in the background. Use documents.wait to poll until it's done, or receive a webhook:
from druckling import DocumentFailedError, WaitTimeoutError
queued = client.documents.create(template="invoice-standard", data=invoice, async_=True)
print(queued.status) # queued
try:
document = client.documents.wait(queued, timeout=120, interval=1)
pdf = client.documents.download(document)
except DocumentFailedError as e:
print("render failed:", e.document.error.message if e.document.error else e.document.status)
except WaitTimeoutError as e:
print("still", e.document.status, "- check again later")wait(document, *, timeout=120.0, interval=1.0) accepts a Document or a document ID and polls documents.get every interval seconds. It returns the document once it's rendered. It raises DocumentFailedError when the document ends failed or expired (e.document holds it), and WaitTimeoutError when the next poll would pass timeout seconds (e.document is the last state seen). With AsyncDruckling, cancel the task to stop waiting early. Each poll is an API request and counts toward your key's rate limit.
Download the file
The file is a PDF, a PNG or an XML e-invoice, depending on the document's format:
documents.download(document)returns it asbytes.documents.download_to(document, path)streams it to a file and returns thepathlib.Path.
Both fetch the file from the document's signed url; your API key isn't sent there.
pdf_bytes = client.documents.download(document)
path = client.documents.download_to(document, document.filename) # PosixPath('INV-2041.pdf')- Pass a document ID instead of a
Documentto fetch the document first and get a fresh signed URL. Do that for documents you stored earlier: a signed URL works for at most 7 days, and never after the file is deleted atexpires_at. - A document that is
failedorexpiredraisesDocumentFailedError. One that is stillqueuedorrenderingraisesDrucklingError; callwaitfirst. - A failed request to the signed URL raises
APIErrorwithcode == "download_failed".
PNG and XML output
Pass format="png" to render the first page as a PNG at 144 dpi instead of a PDF:
preview = client.documents.create(template="invoice-standard", data=invoice, format="png")
print(preview.content_type, preview.pages) # image/png 1
client.documents.download_to(preview, "INV-2041.png")The SDK doesn't support the API's image options yet (image.page to pick another page, image.scale from 0.5 to 4 pixels per point, 36 to 288 dpi). To use them, call the API with httpx and hand the result to the SDK's helpers:
import os
import httpx
from druckling import Document
response = httpx.post(
"https://druckling-nine.vercel.app/v1/documents",
headers={"Authorization": f"Bearer {os.environ['DRUCKLING_API_KEY']}"},
json={"template": "invoice-standard", "data": invoice, "format": "png", "image": {"page": 1, "scale": 4}},
timeout=60,
)
response.raise_for_status()
hi_res = Document.from_dict(response.json())
client.documents.download_to(hi_res, "INV-2041@4x.png")XML output is for e-invoice templates set to XRechnung or Peppol BIS: they render format="xml" by default, content_type is application/xml, and document.einvoice describes the format and profile. Factur-X / ZUGFeRD templates render a PDF/A-3 only. A format the template can't produce raises ValidationError with field == "format". See PNG output and E-invoicing.
Languages
A template can have several languages: a default one plus translations. Pass language to render one of them. For example, after adding German to the invoice-standard template:
template = client.templates.get("invoice-standard")
print(template.language, template.languages) # en ['en', 'de'], default first
rechnung = client.documents.create(
template="invoice-standard",
language="de",
filename="RE-2041.pdf",
data=invoice,
)
print(rechnung.language) # deWithout language the template's default is used. Texts without a translation fall back to the default language; numbers, dates, hyphenation and the PDF's language metadata follow the requested one. A regional tag such as "de-AT" renders "de". A language the template doesn't have raises ValidationError with field == "language". See Languages.
List documents
documents.list() fetches one page of documents, newest first. Iterating the page walks every matching document, fetching the following pages as you go:
for document in client.documents.list(status="failed", template="invoice-standard"):
print(document.id, document.created_at, document.error.message if document.error else "")
page = client.documents.list(limit=20)
page.data # up to 20 documents
page.next_cursor # pass as cursor= to resume later, or None
page.has_next_page() # bool
page.next_page() # the next CursorPage, or NoneFilters: status (queued, rendering, rendered, failed, expired), template (slug), limit (1 to 100, default 25) and cursor. A test key lists test documents, a live key live ones. See List documents.
Templates
for template in client.templates.list():
print(template.slug, template.status, template.latest_version, template.required_fields)
template = client.templates.get("invoice-standard")
template.json_schema # the JSON Schema `data` is validated against
template.sample_data # a payload that renders- Reading templates needs a Full access key; a Render only key gets
PermissionDeniedError. templates.list()returns aListResponsewith every template of the workspace, drafts included. It isn't paginated: iterate it, index it or uselen(), or read.data. See List templates and Retrieve a template.json_schema,sample_data,required_fieldsandlanguagescome from the latest published version, or from the draft if the template was never published.- Only published templates render. Pin a version with
documents.create(..., version=3).
Errors
Every exception the SDK raises derives from druckling.DrucklingError. Errors from the API are APIError subclasses:
DrucklingError
├── APIError
│ ├── ValidationError
│ ├── AuthenticationError
│ ├── PermissionDeniedError
│ ├── NotFoundError
│ ├── ConflictError
│ ├── RenderError
│ ├── RateLimitError
│ │ └── QuotaExceededError
│ └── ServerError
├── APIConnectionError
│ └── APITimeoutError
├── DocumentFailedError
├── WaitTimeoutError
└── WebhookVerificationErrorThe class follows Druckling's error code first, then the HTTP status:
| Exception | When |
|---|---|
ValidationError | 422 schema_validation_failed (data doesn't match the schema) or validation_failed (for example an unknown language, a format the template can't produce, or a broken e-invoice business rule), and 400 malformed requests (bad_request). |
AuthenticationError | 401 unauthorized: missing, invalid or revoked API key. |
PermissionDeniedError | 403 forbidden: the key lacks a permission, for example a Render only key reading templates or managing webhooks. |
NotFoundError | 404 not_found: unknown document, template, webhook endpoint or editor session, or a template without a published version. |
ConflictError | 409 conflict or invalid_state: the resource's current state doesn't allow the request. |
RenderError | render_failed (422) or render_timeout (504): the template couldn't be rendered, or took too long. |
RateLimitError | 429 rate_limited, after the automatic retries. |
QuotaExceededError | 429 quota_exceeded: the plan's document quota is used up. Never retried. |
ServerError | Any other 5xx. |
APIError | Any other HTTP error (such as 413 payload_too_large), a failed download from a signed URL (download_failed), or a successful response that isn't JSON (invalid_response). |
APIConnectionError | No HTTP response: DNS, TLS or network failure. APITimeoutError when the attempt timed out. |
DocumentFailedError | wait or a download found the document failed or expired. e.document holds it. |
WaitTimeoutError | wait ran out of time. e.document is the last state seen. |
WebhookVerificationError | A webhook's signature, timestamp or body didn't verify. |
Every exception has a message attribute. An APIError also carries:
| Attribute | Type | Notes |
|---|---|---|
status | int | HTTP status. |
code | str | Druckling's error code, for example schema_validation_failed. See Errors. |
field | str or None | Dotted path of the offending field, for example customer.name or language. |
errors | list[FieldError] | Every offending field, with field, message and rule (a broken e-invoice business rule such as BR-CO-25, else None). |
document_id | str or None | The failed document recorded for a payload that didn't validate. |
retry_after | float or None | Seconds from the response's Retry-After header, when it has one. |
request_id | str or None | Quote it when you contact support. |
headers | dict[str, str] | Response headers, with lowercase names. |
body | Any | Parsed JSON body, or the raw text when it isn't JSON. |
from druckling import APIError, QuotaExceededError, RateLimitError, ValidationError
try:
client.documents.create(template="invoice-standard", data={"customer": {}})
except ValidationError as e:
print(e.message) # Required field invoice was missing from the request payload
print(e.document_id) # pdf_… (the failed document is kept for your logs)
for error in e.errors:
print(error.field, "→", error.message)
# invoice → missing required field invoice
# line_items → missing required field line_items
# totals → missing required field totals
# customer.name → missing required field customer.name
# customer.address → missing required field customer.address
except QuotaExceededError as e:
notify_billing(e.message)
except RateLimitError:
requeue_later()
except APIError as e:
print(e.status, e.code, e.message, e.request_id)Catch QuotaExceededError before RateLimitError, since it's a subclass.
Retries and timeouts
The client retries failed requests up to max_retries times (default 2):
429 rate_limitedis retried for every request, including renders: a rate-limited request produced no file.429 quota_exceededis never retried; you getQuotaExceededErrorright away.408,5xx, timeouts and connection errors are retried forGETandDELETErequests only, including downloads from signed URLs.POSTrequests (documents.create,webhook_endpoints.create,embed_sessions.create) aren't retried after a5xx, a timeout or a connection error. The API has no idempotency keys yet, so a retry could render the document twice and count twice toward your quota. CatchServerErrorandAPIConnectionErrorand decide yourself, for example by listing recent documents first.
Waits grow exponentially (0.5 s, 1 s, 2 s, … up to 8 s) with jitter. When a response carries a Retry-After header of up to 60 seconds, the SDK waits that long instead; a longer one is raised to you without retrying.
timeout (default 60 seconds) is passed to httpx for each attempt. It applies separately to connecting, sending the request and each read of the response (including waiting for it), not to the attempt as a whole. Synchronous renders happen inside the request, so leave room for large documents, or render them with async_=True. Change it for one block of work with client.with_options(timeout=180).
Webhooks
Druckling can call your HTTPS endpoint when a document is rendered, fails or expires. Deliveries follow the Standard Webhooks spec: webhook-id, webhook-timestamp and webhook-signature headers, signed with HMAC-SHA256 over the raw body.
Verify signatures
verify_webhook(raw_body, headers, secret, *, tolerance=300, now=None) checks the signature and the timestamp, then returns a WebhookEvent. Pass the raw body, before any JSON parsing; re-serialized JSON won't match the signature.
import os
from druckling import WebhookVerificationError, verify_webhook
SECRET = os.environ["DRUCKLING_WEBHOOK_SECRET"] # whsec_…from flask import Flask, request
app = Flask(__name__)
@app.post("/webhooks/druckling")
def druckling_webhook():
try:
event = verify_webhook(request.get_data(), request.headers, SECRET)
except WebhookVerificationError:
return "", 400
if event.type == "document.rendered" and event.document:
save_invoice(event.document.id, event.document.url)
return "", 204| Parameter | Type | Notes |
|---|---|---|
raw_body | bytes, str, bytearray or memoryview | The raw request body. |
headers | any mapping | Flask, Starlette and Django request headers, or a plain dict. Names are matched case-insensitively. |
secret | str | The endpoint's whsec_… signing secret. |
tolerance | int | Maximum age and clock skew of webhook-timestamp, in seconds. Default 300. |
now | int, float or datetime | Override the current time, for tests. |
The WebhookEvent has id, object, type, created_at, test_mode, data (the raw data dict) and document: a Document for document.rendered, document.failed and document.expired, otherwise None.
- Duplicates: a delivery can arrive more than once. Use
event.id(the same as thewebhook-idheader) to ignore repeats; a resent event keeps its ID. - Answer fast: respond with a
2xxwithin 10 seconds and do slow work in a queue. Other answers and timeouts are retried for about 8.6 hours. Don't answer410 Goneunless you want Druckling to stop: it disables the endpoint. - Secret rotation: after you rotate a secret in the dashboard, deliveries are signed with the new and the old secret for 24 hours. Verification passes with either, so deploy the new secret within that window.
- Test events: Send test event on Developers › Webhooks delivers a
webhook.pingevent;event.datais{"object": "ping", "endpoint_id": …, "message": …}andevent.documentisNone. - Batches:
batch.completedevents verify like any other;event.documentisNoneandevent.datais the batch. The SDK'sWebhookEventTypedoesn't listbatch.completedyet, so type checkers flag it, but subscribing to it works at runtime.
verify_webhook_signature(...) takes the same arguments and checks the signature without parsing the body. To test your handler, sign_webhook(secret, msg_id, timestamp, body) returns a valid webhook-signature value (timestamp in Unix seconds or a datetime).
Manage webhook endpoints
Managing endpoints needs a Full access key. Endpoints belong to the key's mode: one created with a test key receives only test-mode events.
endpoint = client.webhook_endpoints.create(
url="https://example.com/webhooks/druckling",
events=["document.rendered", "document.failed"],
description="Invoice mailer",
)
print(endpoint.id, endpoint.secret) # whe_… whsec_…
for e in client.webhook_endpoints.list():
print(e.id, e.url, e.events, e.enabled)
client.webhook_endpoints.get(endpoint.id)
client.webhook_endpoints.delete(endpoint.id) # DeletedObject(id='whe_…', object='webhook_endpoint', deleted=True)The secret is returned only by create, and is left out of the model's repr(): store it now. The URL must be a public https:// URL. See Webhooks for the event payloads and delivery details, and the webhook endpoint reference for every field.
Embedded editor sessions
Let your users edit a template inside your product with Druckling's white-label editor. Allow your app's origin in Settings › Embed first. Then, when a signed-in user opens the editor, your backend creates a short-lived session with a Full access key and hands its url to that user's browser:
from flask import Flask
from flask_login import current_user, login_required
from druckling import Druckling
app = Flask(__name__)
client = Druckling()
@app.post("/api/template-editor")
@login_required
def template_editor():
session = client.embed_sessions.create(
template="invoice-standard",
permissions={"publish": True},
user={"id": str(current_user.id), "name": current_user.name},
theme={"mode": "system", "accent": "#0f766e"},
expires_in=1800,
)
return {"url": session.url}, 200, {"Cache-Control": "no-store"}| Argument | Default | Notes |
|---|---|---|
template | required | Slug of the template to edit. |
permissions | {"publish": False, "assistant": False} | publish lets the user publish new versions; by default they edit the draft and you publish. assistant offers the AI assistant on plans that include it; the returned session.permissions.assistant says whether it's on. |
user | none | {"id": …, "name": …}: shown in request logs and on the versions the user publishes. |
theme | {"mode": "light"} | mode is light, dark or system; accent is a #rgb or #rrggbb color. |
expires_in | 1800 | Seconds until the session ends, 60 to 3600. |
In the browser, mount the url with mountEditor from @druckling/embed, or load it in an iframe yourself. See Embedded editor, and the reference for creating and revoking sessions.
- The
urlcarries the session token in its fragment (#token=…). Give it only to the signed-in user's browser; never log, cache or store it. Onlycreatereturns it, and it's left out of the model'srepr(). client.embed_sessions.revoke(session.id)ends a session right away, for example when the user signs out. It returns the session withstatus == "revoked"andurlset toNone. Revoking twice is fine.createraisesConflictError(invalid_state) until an origin is allowed in Settings › Embed,PermissionDeniedErrorfor a Render only key,ValidationErrorfor bad options, andRateLimitErrorbeyond about 60 sessions a minute per workspace.
Test and live keys
The API key decides the mode of every request:
dr_test_…keys are for development. Test renders are free and never count toward your plan's quota. Documents you list, webhook endpoints and their events stay separate from live data, and every resource hastest_mode == True.dr_live_…keys are for production. Live renders count toward your plan's quota.
client.mode tells you which one a client uses. See Test mode.