# Authentication (/docs/authentication) > Authenticate API requests with a secret API key, choose its mode and permission, and rotate or revoke it safely. Every request to the Druckling API is authenticated with a secret API key. A key belongs to one workspace and decides three things: which workspace the request acts in, whether it runs in live or test mode, and what it's allowed to do. ## Send your API key [#send-your-api-key] Send the key in the `Authorization` header with the `Bearer` scheme: ```bash tab="Authorization" curl https://druckling-nine.vercel.app/v1/documents \ -H "Authorization: Bearer $DRUCKLING_API_KEY" ``` ```bash tab="x-api-key" curl https://druckling-nine.vercel.app/v1/documents \ -H "x-api-key: $DRUCKLING_API_KEY" ``` Both headers work the same way. If a request has both, the `Authorization: Bearer` header is used. The SDKs send `Authorization: Bearer` and read the key from the `DRUCKLING_API_KEY` environment variable unless you pass one explicitly. See [SDKs](/docs/sdks). The same keys authenticate the hosted [MCP server](/docs/guides/mcp), with the same permissions. ## Key format [#key-format] A key is a mode prefix followed by 64 random letters: | Prefix | Mode | | --- | --- | | `dr_live_` | Live: production renders that count toward your plan's quota | | `dr_test_` | Test: free renders, kept apart from live data | The prefix is the only thing that decides the mode: there's no header or parameter to switch it. See [Test mode](/docs/concepts/test-mode) for what's separated between the two. Druckling stores a hash of the key, not the key itself, so the full key is shown only once, when you create it. The dashboard identifies keys by their name and their first characters, for example `dr_live_xKpQ••••`. Keys don't expire; they work until you revoke them. ## Permissions [#permissions] Each key has one of two permission levels. Pick **Render only** for services that only render documents, and **Full access** only where you need templates, webhooks or the embedded editor. | | Render only | Full access | | --- | --- | --- | | Scopes | `documents:create`, `documents:read` | `documents:create`, `documents:read`, `templates:read`, `templates:write`, `webhooks:manage` | | [Documents](/docs/api-reference/documents/create): render, retrieve, list | Yes | Yes | | [Batches](/docs/api-reference/batches/create): start, retrieve, list, list documents, cancel | Yes | Yes | | [Share links](/docs/api-reference/share-links/create): create, list, revoke | Yes | Yes | | [Templates](/docs/api-reference/templates/list): list, retrieve with JSON Schema | No | Yes | | [Webhook endpoints](/docs/api-reference/webhooks/create): create, list, retrieve, delete | No | Yes | | [Embedded editor sessions](/docs/api-reference/embedded-editor/create): create, revoke | No | Yes | | MCP server: render and read documents | Yes | Yes | | MCP server: list, read, create, edit and publish templates | No | Yes | A render-only key can render any published template, as long as you know its slug. It just can't list templates or read their schemas. ## Keys and workspaces [#keys-and-workspaces] A key works in the workspace it was created in. Everything it creates, such as documents, batches and webhook endpoints, belongs to that workspace, and it can't reach any other. If you belong to several workspaces, create a key in each. A key isn't tied to the person who created it. It keeps working when that person leaves the workspace. ## Manage keys [#manage-keys] Keys are managed in the dashboard under **Developers › API keys**. Owners and admins can create and revoke keys. Members can see the list, with each key's name, mode, permission, when it was last used and when it was created, but can't change it. Keys can't be renamed or edited. To change a key's mode or permission, create a new key and revoke the old one. ### Create a key [#create-a-key] 1. Go to **Developers › API keys** and click **Create API key**. 2. Name the key after the service that uses it, for example `billing-service`. Keep the name to 32 characters or fewer. 3. Choose the mode, **Test** or **Live**, and the permission, **Render only** or **Full access**. 4. Click **Create key**, copy the key and store it in your server's environment or secret manager. You won't be able to see it again. ### Rotate a key [#rotate-a-key] There's no in-place rotation. Both keys work at the same time, so rotate without downtime: 1. Create a new key with the same mode and permission. 2. Deploy it everywhere the old key is used. 3. Check that the old key's **Last used** time no longer changes. 4. Revoke the old key. ### Revoke a key [#revoke-a-key] Open the key's actions menu in the list, choose **Revoke key** and confirm. Requests that use it fail with `401` right away. Revoking can't be undone. ## Keep keys secret [#keep-keys-secret] API keys are server-side secrets: - Keep them in environment variables or a secret manager, never in source control. - Never ship a key to a browser or a mobile app. Anyone who has it can act in your workspace: render documents (on your quota, with a live key) and, with full access, read your templates and manage your webhooks and editor sessions. - To let your users edit templates in your product, create a short-lived [embedded editor session](/docs/guides/embedded-editor) on your server and give its URL to the browser. A session can only work on one template and expires after at most an hour. - To give someone a rendered document, send them a [share link](/docs/concepts/share-links) or the document's signed `url`. Neither needs a key. If a key leaks, revoke it, create a replacement, and look through **Developers › Logs** for requests you don't recognize. The Logs page shows the dashboard's current mode, so switch to test mode to see a test key's requests. ## Authentication errors [#authentication-errors] Authentication errors have the same shape as every other [error](/docs/concepts/errors): ```json { "defined": false, "code": "UNAUTHORIZED", "status": 401, "message": "Invalid or revoked API key", "data": { "code": "unauthorized", "field": null } } ``` | Status | `data.code` | Message | Cause | | --- | --- | --- | --- | | 401 | `unauthorized` | Missing API key. Send it as `x-api-key` or `Authorization: Bearer`. | No key in the request. | | 401 | `unauthorized` | Invalid or revoked API key | The key is mistyped, incomplete or revoked. | | 403 | `forbidden` | This API key does not have the templates:read permission | A render-only key called `GET /v1/templates` or `GET /v1/templates/{slug}`. | | 403 | `forbidden` | This API key does not have the webhooks:manage permission | A render-only key listed or retrieved webhook endpoints. | | 403 | `forbidden` | Only owners and admins can manage webhooks | A render-only key created or deleted a webhook endpoint. | | 403 | `forbidden` | Creating editor sessions needs a full-access API key (templates:write) | A render-only key created or revoked an embedded editor session. | | 429 | `rate_limited` | Too many requests for this API key | The key sent too many requests in a short time. See [Plans and limits](/docs/concepts/plans-and-limits). | Requests that fail with the `401` and `429` errors above aren't recorded under **Developers › Logs**. Requests rejected with `403` are. # Documents (/docs/concepts/documents) > What a document is, how it moves from request to file, and how to render, wait for, list, download and keep track of documents. A document is one render request and its result. Each call to [`POST /v1/documents`](/docs/api-reference/documents/create) that Druckling accepts creates one, whether it renders right away, is queued for later, or fails validation. The document records what you asked for (template, version, format, language) and, once it renders, points at the file: a PDF, a PNG or an e-invoice XML. You poll documents, list them, download their files, [share them](/docs/concepts/share-links) and receive [webhooks](/docs/guides/webhooks) about them. Document IDs start with `pdf_`, whatever the format. ## Lifecycle [#lifecycle] A document moves through these statuses: | Status | What it means | | --- | --- | | `queued` | Accepted with `async: true` and waiting for a render worker. | | `rendering` | The file is being rendered. A synchronous request returns only after this. | | `rendered` | The file is stored and `url` holds a signed download link. | | `failed` | Validation or rendering failed. `error` says why. This status is final. | | `expired` | The file was deleted at the end of the retention period. The record stays. | `rendered` and `failed` are the outcomes of a render; `expired` follows `rendered` once [retention](#retention) ends. A few things to know about the transitions: - **Validation comes first.** Druckling checks `data` against the template's [JSON Schema](/docs/concepts/variables) before rendering or queueing anything. A payload that doesn't match still creates a document, with status `failed`, and the request fails with `422`. The error body carries the new document's ID in `data.documentId`, so you can find the failed attempt later. - **Some requests never create a document.** A malformed request (`400`), a missing or invalid key (`401`), a missing permission (`403`), an unknown template or version (`404`), a `format` or `image` option the template doesn't support (`422`) and an exhausted quota (`429`) are rejected before a document exists. See [Errors](/docs/concepts/errors). - **Webhooks follow the status.** `document.rendered` fires when a document reaches `rendered`, `document.failed` when it reaches `failed` (validation failures included), and `document.expired` when its file is deleted. ## Output formats [#output-formats] The `format` field decides what the document contains. When you leave it out, the template decides. | `format` | `content_type` | When to use it | | --- | --- | --- | | `pdf` | `application/pdf` | The default for every template except XRechnung and Peppol BIS e-invoice templates. Factur-X / ZUGFeRD templates produce a PDF/A-3 with the invoice XML embedded. | | `png` | `image/png` | One page as an image, for previews and thumbnails. Pick the page with `image.page` (default 1) and the resolution with `image.scale` (pixels per point, 0.5 to 4, default 2 = 144 dpi). | | `xml` | `application/xml` | XRechnung and Peppol BIS e-invoice templates, which produce only XML. | The template has to support the format you ask for, otherwise the request fails with `422 validation_failed` on `format`: - Factur-X templates render to `pdf` only. - XRechnung and Peppol BIS templates render to `xml` only, and `xml` needs one of those templates. - `image` options are only allowed with `format: "png"` (`422` on `image`). - A template's PDF/A or PDF/UA setting applies to PDFs only. A PNG of such a template renders normally and notes this on its timeline. See [PNG output](/docs/guides/png-output) and [E-invoicing](/docs/guides/e-invoicing) for the details of each. ## Synchronous rendering [#synchronous-rendering] By default the request waits for the render and returns the finished document with `200 OK`: ```bash tab="cURL" curl https://druckling-nine.vercel.app/v1/documents \ -H "Authorization: Bearer $DRUCKLING_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "template": "invoice-standard", "filename": "INV-2041", "data": { "invoice": { "number": "INV-2041", "due_date": "2026-11-22" }, "customer": { "name": "Northwind Ltd.", "address": "12 Pier St, Leeds" }, "line_items": [ { "description": "Design system audit", "qty": 12, "rate": 180, "amount": 2160 } ], "totals": { "subtotal": 2160, "tax": 172.8, "amount": 2332.8 } } }' ``` ```ts tab="TypeScript" import Druckling from "@druckling/sdk"; const druckling = new Druckling(); const document = await druckling.documents.create({ template: "invoice-standard", filename: "INV-2041", data: { invoice: { number: "INV-2041", due_date: "2026-11-22" }, customer: { name: "Northwind Ltd.", address: "12 Pier St, Leeds" }, line_items: [{ description: "Design system audit", qty: 12, rate: 180, amount: 2160 }], totals: { subtotal: 2160, tax: 172.8, amount: 2332.8 }, }, }); ``` ```python tab="Python" from druckling import Druckling client = Druckling() document = client.documents.create( template="invoice-standard", filename="INV-2041", data={ "invoice": {"number": "INV-2041", "due_date": "2026-11-22"}, "customer": {"name": "Northwind Ltd.", "address": "12 Pier St, Leeds"}, "line_items": [{"description": "Design system audit", "qty": 12, "rate": 180, "amount": 2160}], "totals": {"subtotal": 2160, "tax": 172.8, "amount": 2332.8}, }, ) ``` ```php tab="PHP" $druckling = new Druckling\Druckling(); $document = $druckling->documents->create( template: 'invoice-standard', filename: 'INV-2041', data: [ 'invoice' => ['number' => 'INV-2041', 'due_date' => '2026-11-22'], 'customer' => ['name' => 'Northwind Ltd.', 'address' => '12 Pier St, Leeds'], 'line_items' => [['description' => 'Design system audit', 'qty' => 12, 'rate' => 180, 'amount' => 2160]], 'totals' => ['subtotal' => 2160, 'tax' => 172.8, 'amount' => 2332.8], ], ); ``` ```json title="Response" { "id": "pdf_8Qw2kLm3nP0aB1cD", "object": "document", "status": "rendered", "template": "invoice-standard", "version": 1, "filename": "INV-2041.pdf", "format": "pdf", "content_type": "application/pdf", "image": null, "pages": 1, "size_bytes": 48213, "url": "https://…", "expires_at": "2026-11-26T09:14:03.120Z", "error": null, "einvoice": null, "batch": null, "language": "en", "test_mode": true, "created_at": "2026-10-27T09:14:02.384Z" } ``` ### Time limits [#time-limits] Typesetting a document is limited to **10 seconds**. A render that takes longer is stopped: the request fails with `504` and code `render_timeout`, and the document ends up `failed` with the same code. The whole request can take longer than the typesetting step, since Druckling also fetches images, may wait for a free render worker, and stores the file. Give your HTTP client a timeout of about 60 seconds, which is what the SDKs use by default. If the template can't be rendered (a Typst error, or more pages than the [page limit](#pages-and-size)), the request fails with `422 render_failed` and the document is `failed`. ## Asynchronous rendering [#asynchronous-rendering] Set `async: true` to queue the render and get an answer right away. Druckling validates `data` first, so schema errors still come back on this request as a `422`. A valid request returns `202 Accepted` with status `queued`, `url: null`, and the document ID you use to follow it: ```bash curl https://druckling-nine.vercel.app/v1/documents \ -H "Authorization: Bearer $DRUCKLING_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "template": "invoice-standard", "async": true, "data": { "invoice": { "number": "INV-2042", "due_date": "2026-11-29" }, "customer": { "name": "Northwind Ltd.", "address": "12 Pier St, Leeds" }, "line_items": [ { "description": "Workshop facilitation", "qty": 2, "rate": 640, "amount": 1280 } ], "totals": { "subtotal": 1280, "tax": 102.4, "amount": 1382.4 } } }' ``` ```json title="Response" { "id": "pdf_3Rt8vXq1mK6sJ2nB", "object": "document", "status": "queued", "template": "invoice-standard", "version": 1, "filename": "invoice-standard-3Rt8vXq1.pdf", "format": "pdf", "content_type": "application/pdf", "image": null, "pages": null, "size_bytes": null, "url": null, "expires_at": null, "error": null, "einvoice": null, "batch": null, "language": "en", "test_mode": true, "created_at": "2026-10-27T09:20:11.042Z" } ``` Choose asynchronous rendering when the caller shouldn't wait, for example inside a web request handler, or when you already process [webhooks](/docs/guides/webhooks). It doesn't buy a render more time: the same 10-second typesetting limit applies. To render many documents at once, use a [batch](/docs/guides/batches) instead of many separate requests. A queued render that fails, for example with a Typst error or a timeout, is final: Druckling doesn't render that document again. Payload [size limits](/docs/concepts/plans-and-limits#payload-and-render-limits) are checked when the document renders, so an oversized asynchronous payload shows up as a `failed` document with `error.code: "payload_too_large"`, not as an error on the request. ## Wait for a document [#wait-for-a-document] ### Use webhooks [#use-webhooks] A [webhook endpoint](/docs/guides/webhooks) subscribed to `document.rendered` and `document.failed` tells you the moment a document is done. The event's `data` is the full document, including a freshly signed `url`. This is the recommended way to follow asynchronous renders: it costs no API requests and has no polling delay. ### Poll [#poll] Without webhooks, retrieve the document with [`GET /v1/documents/{id}`](/docs/api-reference/documents/get) until its status is `rendered`, `failed` or `expired`. Each poll is an API request and counts toward your key's [rate limit](/docs/concepts/plans-and-limits#rate-limits), so poll every couple of seconds rather than in a tight loop, and stop after a deadline. ```bash tab="cURL" id="pdf_3Rt8vXq1mK6sJ2nB" for attempt in $(seq 1 30); do doc=$(curl -s "https://druckling-nine.vercel.app/v1/documents/$id" \ -H "Authorization: Bearer $DRUCKLING_API_KEY") status=$(echo "$doc" | jq -r .status) case "$status" in rendered) echo "$doc" | jq -r .url; break ;; failed|expired) echo "$doc" | jq .error; exit 1 ;; esac sleep 2 done ``` ```ts tab="TypeScript" const queued = await druckling.documents.create({ template: "invoice-standard", data, async: true }); const document = await druckling.documents.wait(queued, { intervalMs: 2_000, timeoutMs: 60_000 }); console.log(document.url); ``` ```python tab="Python" queued = client.documents.create(template="invoice-standard", data=data, async_=True) document = client.documents.wait(queued, interval=2, timeout=60) print(document.url) ``` ```php tab="PHP" $queued = $druckling->documents->create(template: 'invoice-standard', data: $data, async: true); $document = $druckling->documents->wait($queued, timeout: 60, interval: 2); echo $document->url; ``` The SDK wait helpers return the document once it's `rendered`. They throw a document-failed error when it ends up `failed` or `expired`, and a wait-timeout error when the deadline passes first. Their default is a poll every second for up to 120 seconds. ## List documents [#list-documents] [`GET /v1/documents`](/docs/api-reference/documents/list) returns the documents of your API key's mode, newest first. A test key lists test documents and a live key lists live ones. | Parameter | Description | | --- | --- | | `limit` | Documents per page, 1 to 100. Default 25. | | `cursor` | The `next_cursor` of the previous page. Treat it as opaque. | | `status` | Only documents with this status, e.g. `failed`. | | `template` | Only documents rendered from this template slug. | The response has `object: "list"`, the page in `data`, and `next_cursor`, which is `null` on the last page: ```bash curl "https://druckling-nine.vercel.app/v1/documents?status=failed&template=invoice-standard&limit=50" \ -H "Authorization: Bearer $DRUCKLING_API_KEY" ``` To get the next page, repeat the request with `cursor` set to `next_cursor`. The SDKs do this for you when you iterate: ```ts tab="TypeScript" for await (const doc of druckling.documents.list({ status: "failed" })) { console.log(doc.id, doc.filename); } ``` ```python tab="Python" for doc in client.documents.list(status="failed"): print(doc.id, doc.filename) ``` ```php tab="PHP" foreach ($druckling->documents->list(status: 'failed') as $doc) { echo $doc->id, ' ', $doc->filename, PHP_EOL; } ``` Documents in a list always have `url`, `expires_at` and `error` set to `null`, even when the document has a file or an error. Retrieve a document by ID to get its download link, its expiry and the reason it failed. ## File names [#file-names] `filename` sets the file's name, up to 200 characters. Druckling cleans it up: - Slashes, backslashes and control characters are removed, and surrounding whitespace is trimmed. - The extension always matches the format. Druckling adds `.pdf`, `.png` or `.xml`, and replaces one of those that doesn't match: `INV-2041` becomes `INV-2041.pdf`, and `INV-2041.png` rendered as a PDF becomes `INV-2041.pdf`. - Without a `filename`, the name is the template slug plus part of the document ID, e.g. `invoice-standard-8Qw2kLm3.pdf`. Names don't have to be unique. [Share links](/docs/concepts/share-links) serve the file under this name, and the dashboard shows it. The signed `url` doesn't use it: the link's path ends in the document ID, so name the file yourself when you save a download. ## Pages and size [#pages-and-size] `pages` is the page count of a PDF, `1` for a PNG and `null` for XML. `size_bytes` is the size of the stored file. Both are `null` until the document is rendered. A document can have as many pages as your plan allows: 50 on Free, 100 on Starter, 200 on Pro and 500 on Business. A longer one fails with `422 render_failed` ("The document has 64 pages; your plan allows 50 per document"); the error's `data.pages` holds the count and `data.limit` the limit. The limit applies to the laid-out document, so it also applies when you render a single page as a PNG. See [Plans and limits](/docs/concepts/plans-and-limits#payload-and-render-limits) for the other limits. ## Download the file [#download-the-file] A rendered document's `url` is a signed link to the file in Druckling's private storage. Whoever has the link can download the file without an API key, so treat it like a password: keep it out of logs and public pages, and don't send your API key along to it. ```bash tab="cURL" url=$(curl -s "https://druckling-nine.vercel.app/v1/documents/pdf_8Qw2kLm3nP0aB1cD" \ -H "Authorization: Bearer $DRUCKLING_API_KEY" | jq -r .url) curl -o INV-2041.pdf "$url" ``` ```ts tab="TypeScript" import { writeFile } from "node:fs/promises"; const bytes = await druckling.documents.download("pdf_8Qw2kLm3nP0aB1cD"); await writeFile("INV-2041.pdf", bytes); ``` ```python tab="Python" client.documents.download_to("pdf_8Qw2kLm3nP0aB1cD", "INV-2041.pdf") ``` ```php tab="PHP" $druckling->documents->downloadTo('pdf_8Qw2kLm3nP0aB1cD', 'INV-2041.pdf'); ``` How the link behaves: - **It's short-lived.** A link works for up to 7 days after the API returned it, and never after the document's `expires_at`. The API doesn't report a link's own expiry, so don't store links for later. - **Every read signs a new one.** Retrieving the document returns a fresh link, and so does each `document.rendered` webhook. When you need the file later, retrieve the document again. The SDK download helpers do this when you pass an ID. - **It's `null` when there's nothing to download**: while the document is `queued` or `rendering`, when it `failed` or `expired`, once `expires_at` has passed, and in [list results](#list-documents). To give the file to someone who doesn't use your API, create a [share link](/docs/concepts/share-links) instead. ## Retention [#retention] Druckling keeps rendered files for a limited time on every plan: | What | How long | | --- | --- | | Rendered file | 30 days after rendering. `expires_at` says when it's deleted. | | Signed download link | Up to 7 days after it was returned, and never past `expires_at`. | | Request body shown in the dashboard | 30 days, then removed. Bodies larger than 64 KB aren't stored. | | Document record (status, file name, pages, timeline) | 1 year. After that, retrieving the document returns `404`. | A daily cleanup job deletes files whose `expires_at` has passed, sets their documents to `expired`, and sends `document.expired`. Until the job has run, such a document still reads `rendered`, but its `url` is already `null`. Share links to the document stop working at `expires_at` too. Retention is the same on every plan. If you need files for longer, download them when they're rendered (for example from your `document.rendered` webhook handler) and store them yourself. ## Failed documents [#failed-documents] A `failed` document has an `error` object: ```json { "id": "pdf_6Jd2pRw9tL4xQ8sM", "object": "document", "status": "failed", "template": "invoice-standard", "version": 1, "filename": "INV-2043.pdf", "format": "pdf", "content_type": "application/pdf", "image": null, "pages": null, "size_bytes": null, "url": null, "expires_at": null, "error": { "code": "schema_validation_failed", "message": "Required field customer.address was missing from the request payload", "field": "customer.address" }, "einvoice": null, "batch": null, "language": "en", "test_mode": true, "created_at": "2026-10-27T09:31:45.906Z" } ``` `field` is the dotted path of the offending value, with array indexes as numbers, e.g. `line_items.2.qty`. It's `null` when the error isn't about one field. The codes you'll see on documents: | `error.code` | Why the document failed | | --- | --- | | `schema_validation_failed` | `data` doesn't match the template's JSON Schema. | | `validation_failed` | A rule the schema can't express, such as an e-invoice business rule (`BR-CO-25` and so on), or a PNG `image.page` past the end of the document. | | `render_failed` | The template couldn't be rendered, or the document had more pages than your plan allows. | | `render_timeout` | Typesetting took longer than 10 seconds. | | `payload_too_large` | `data` exceeded a [payload limit](/docs/concepts/plans-and-limits#payload-and-render-limits). | | `canceled` | The document was an item of a [batch](/docs/guides/batches) that was canceled before it rendered. | Rarely, you may also see `rate_limited` (the render engine was overloaded), or `not_found` (the template version disappeared before a queued render started). The API has no retry endpoint: fix the payload or the template and send a new request. See [Errors](/docs/concepts/errors) for every code and what to do about it. ## In the dashboard [#in-the-dashboard] **Documents** lists the documents of the mode you're in; switch with **Test mode** in the sidebar. Filter by period, status, template and API key, search by file name or document ID, and export the list as CSV. The **Retention** button shows how long files and links are kept. Click a document to open its details: - Its status, format, mode, template version and creation time. - For a failed document, the error and the offending field, plus **Retry with test data**, which renders the template again with its sample data as a new document in the same mode. - For a rendered document, the page count, file size and render time, a download button, and its [share links](/docs/concepts/share-links). - The **Timeline**: when the request was received, validated, queued, rendered, stored or failed, retries, notes (for example that a PDF standard doesn't apply to a PNG), and expiry. - The **Request body** as Druckling received it, until it's removed after 30 days. - The API key that created it, the language, the batch it belongs to and the engine versions. ## Next steps [#next-steps] Give people a link to a rendered document without an API key. Get notified when documents render, fail or expire. Render one page as an image for previews and thumbnails. Produce Factur-X, ZUGFeRD, XRechnung and Peppol BIS invoices. # Errors (/docs/concepts/errors) > The shape of Druckling API errors, every error code and its HTTP status, and how to retry without rendering a document twice. Druckling answers every request with a conventional HTTP status code: `2xx` when it worked, `4xx` when something about the request needs to change, and `5xx` when something went wrong on Druckling's side. Errors come with a JSON body that tells you what happened and, for most errors, which field caused it. ## Error format [#error-format] ```json title="422 Unprocessable Content" { "defined": false, "code": "UNPROCESSABLE_CONTENT", "status": 422, "message": "Required field customer.address was missing from the request payload", "data": { "code": "schema_validation_failed", "field": "customer.address", "documentId": "pdf_6Jd2pRw9tL4xQ8sM", "errors": [ { "field": "customer.address", "message": "missing required field customer.address" }, { "field": "invoice.due_date", "message": "invoice.due_date must be a date like 2026-11-22" } ] } } ``` Depending on the error, `data` holds more fields, such as `documentId`, `errors`, `retryAfter` or `diagnostics`. They're described with each code below. A few responses don't have `data.code`: request validation errors (`400`), unexpected server errors (`500`) and requests to an unknown endpoint (`404`). Fall back to the top-level `code` for those, which is what the SDKs do. ## Request validation errors [#request-validation-errors] Before a request reaches Druckling's own checks, its shape is validated against the API's schema: required fields, types, allowed values and ranges. A request that doesn't match fails with `400 BAD_REQUEST`, and `data.issues` lists every problem: ```bash curl https://druckling-nine.vercel.app/v1/documents \ -H "Authorization: Bearer $DRUCKLING_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "data": { "invoice": { "number": "INV-2041" } }, "async": "yes" }' ``` ```json title="400 Bad Request" { "defined": false, "code": "BAD_REQUEST", "status": 400, "message": "Input validation failed", "data": { "issues": [ { "expected": "string", "code": "invalid_type", "path": ["template"], "message": "Invalid input: expected string, received undefined" }, { "expected": "boolean", "code": "invalid_type", "path": ["async"], "message": "Invalid input: expected boolean, received string" } ] } } ``` Each issue's `path` is an array of keys and array indexes. A body that isn't valid JSON gets `400` with the message "Malformed request…" and no `data`. Fields the API doesn't know are ignored, not rejected. The API key is checked first, so a request with a missing or invalid key gets `401` even if its body is also invalid. ## Error codes [#error-codes] | `data.code` | Status | `code` | When it happens | | --- | --- | --- | --- | | `unauthorized` | `401` | `UNAUTHORIZED` | The API key is missing ("Missing API key…"), or it's invalid or revoked ("Invalid or revoked API key"). | | `forbidden` | `403` | `FORBIDDEN` | The key lacks a permission, for example a Render only key reading templates, managing webhooks or creating editor sessions. | | `not_found` | `404` | `NOT_FOUND` | No such document, batch, share link, webhook endpoint or template. Also a template without a published version (`field: "template"`) and an unknown `version` (`field: "version"`). | | `conflict` | `409` | `CONFLICT` | A count limit is reached: 20 active share links per document, or 20 webhook endpoints per workspace. | | `invalid_state` | `409` | `CONFLICT` | The object can't do that right now: sharing a document that isn't `rendered`, canceling a batch that already finished, or creating an editor session before any origin is allowed in **Settings › Embed**. | | `stale_revision` | `409` | `CONFLICT` | Only in the dashboard and editors: someone else saved the template first. The REST API doesn't return it. | | `schema_validation_failed` | `422` | `UNPROCESSABLE_CONTENT` | `data` doesn't match the template's JSON Schema: a required field is missing, or a value has the wrong type or format. | | `validation_failed` | `422` | `UNPROCESSABLE_CONTENT` | The request is well-formed but breaks a rule the schema can't express: a `format` or `image` option the template doesn't support, a PNG `image.page` past the end of the document, a `language` the template doesn't have, an e-invoice business rule, or `data` nested deeper than 32 levels. | | `payload_too_large` | `413` | `PAYLOAD_TOO_LARGE` | `data` is larger than 1,000,000 bytes, an array in it has more than 10,000 items, or a batch's `items` exceed 4 MB. | | `quota_exceeded` | `429` | `QUOTA_EXCEEDED` | Your plan's daily or monthly live document quota is used up. | | `rate_limited` | `429` | `TOO_MANY_REQUESTS` | The API key made too many requests, too many editor sessions were created at once, or the render engine is busy. | | `render_failed` | `422` | `UNPROCESSABLE_CONTENT` | The template couldn't be rendered: a Typst error, more pages than your plan allows, or an unexpected failure while rendering or storing the file. | | `render_timeout` | `504` | `GATEWAY_TIMEOUT` | Typesetting took longer than 10 seconds and was stopped. | And the responses without `data.code`: | Status | `code` | When it happens | | --- | --- | --- | | `400` | `BAD_REQUEST` | The request doesn't match the API's schema, or the body isn't valid JSON. See [request validation errors](#request-validation-errors). | | `404` | `NOT_FOUND` | The path doesn't exist. The body is just `{ "code": "NOT_FOUND", "message": "Unknown endpoint" }`. | | `500` | `INTERNAL_SERVER_ERROR` | Something unexpected went wrong on Druckling's side. The message is "Internal server error". | Limits behind these codes are listed in [Plans and limits](/docs/concepts/plans-and-limits). ## Validation errors [#validation-errors] Druckling validates a render request in two steps, and the code tells you which one failed: - **`schema_validation_failed`**: `data` doesn't match the template's [JSON Schema](/docs/concepts/variables). `data.field` is the first problem, with missing fields first, and `data.errors` lists every problem as `{ field, message }`. - **`validation_failed`**: the payload has the right shape but breaks a rule, or the request asks for something the template can't do. For e-invoice templates, `data.errors` lists the broken business rules, each with a `rule` such as `BR-CO-25`, and the rule's ID also appears in the message. See [E-invoicing](/docs/guides/e-invoicing). Field paths are dotted, and array indexes are numbers: `line_items.2.qty` is the `qty` of the third line item. When `data` fails either check, Druckling still creates a document, in status `failed`, and `data.documentId` holds its ID. That's how the attempt shows up in **Documents** in the dashboard, and why it triggers a `document.failed` [webhook](/docs/guides/webhooks). It doesn't count toward your quota. Errors about the request itself, such as an unsupported `format` or an unknown `language`, are rejected before a document is created. ### Batch validation errors [#batch-validation-errors] [`POST /v1/batches`](/docs/api-reference/batches/create) validates every item before rendering anything. If any item is invalid, nothing is rendered, no documents are created, and the answer is `422`. `data.field` points into the first invalid item, `data.invalidItems` counts the invalid items, and `data.errors` lists the first problem of each of the first 20 invalid items, with `field` relative to that item's `data`: ```json title="422 Unprocessable Content" { "defined": false, "code": "UNPROCESSABLE_CONTENT", "status": 422, "message": "Item 3: Required field customer.address was missing from the request payload (2 of 50 items are invalid)", "data": { "code": "schema_validation_failed", "field": "items.3.data.customer.address", "invalidItems": 2, "errors": [ { "index": 3, "field": "customer.address", "message": "Required field customer.address was missing from the request payload" }, { "index": 17, "field": "invoice.due_date", "message": "Required field invoice.due_date was missing from the request payload" } ] } } ``` See [Batches](/docs/guides/batches) for the whole flow. ## Render errors [#render-errors] `render_failed` (`422`) means the template couldn't be turned into a file with this payload: - **A Typst error.** `data.diagnostics` lists the engine's messages, each with a `severity`, a `message`, and the template block it came from when Druckling can tell. Open the template in the editor with the same data to see the problem. - **Too many pages.** "The document has 64 pages; the limit is 50", with the count in `data.pages`. - **An unexpected failure**, such as "Rendering failed unexpectedly". These can be temporary. `render_timeout` (`504`) means typesetting took longer than 10 seconds and was stopped. In both cases the document is recorded as `failed` with the same `error.code`, and it doesn't count toward your quota. With `async: true` you don't get these errors on the request: the document ends up `failed` instead, and `document.failed` tells you. See [Documents](/docs/concepts/documents#failed-documents). ## Retrying [#retrying] Whether a retry can help depends on the error: | Error | Retry? | | --- | --- | | `429 rate_limited` | Yes, after a pause. Wait for the `Retry-After` header (also in `data.retryAfter`). The per-key limit counts 120 requests a minute. See [rate limits](/docs/concepts/plans-and-limits#rate-limits). | | `429 quota_exceeded` | No. Wait for the quota to reset, upgrade, or use a test key while developing. | | `500` and other `5xx` | Yes for `GET` and `DELETE`, with exponential backoff. For `POST`, read [idempotency](#idempotency) first. | | `504 render_timeout` | At most once. If it times out again, make the document lighter, for example with fewer table rows or images. | | `422 render_failed` | Not until you fix the template or the payload, unless it's an unexpected failure without `data.diagnostics`. | | `400`, `401`, `403`, `404`, `409`, `413`, other `422` | No. Fix the request first. | | No response (network error, client timeout) | Yes for `GET` and `DELETE`. For `POST`, the server may have done the work: read [idempotency](#idempotency). | Each `POST /v1/documents` that Druckling accepts creates a new document, and attempts that failed validation or rendering stay in your document list as `failed` documents. ## Idempotency [#idempotency] The API doesn't support idempotency keys. An `Idempotency-Key` header is ignored, and every `POST /v1/documents` that passes validation renders a new document, which counts toward your quota in live mode. Duplicates happen when a request reaches Druckling but the response never reaches you: the connection drops, or your client times out during a synchronous render. The document may have rendered anyway. To keep this from creating duplicates: - **Name documents uniquely.** Set `filename` to something unique, such as the invoice number. After a network error or a `5xx`, [list recent documents](/docs/api-reference/documents/list) for the template and look for that file name before you render again. - **Store the ID right away.** Once you have a document's ID, everything else (retrieving, waiting, downloading) is a `GET` that is safe to retry. - **Shorten the window.** With `async: true` the request returns as soon as the payload is validated, so a dropped connection during a slow render can't leave you without the document ID. ```ts title="render-once.ts" import Druckling, { APIConnectionError, ServerError } from "@druckling/sdk"; const druckling = new Druckling(); export async function renderInvoice(number: string, data: Record) { const filename = `${number}.pdf`; try { return await druckling.documents.create({ template: "invoice-standard", filename, data }); } catch (error) { if (!(error instanceof APIConnectionError || error instanceof ServerError)) throw error; const recent = await druckling.documents.list({ template: "invoice-standard", limit: 20 }); const existing = recent.data.find((doc) => doc.filename === filename && doc.status !== "failed"); if (existing) return druckling.documents.wait(existing.id); return druckling.documents.create({ template: "invoice-standard", filename, data }); } } ``` The same applies to [`POST /v1/batches`](/docs/api-reference/batches/create): sending it twice starts two batches. ### What the SDKs retry [#what-the-sdks-retry] The SDKs retry up to 2 times by default. They resend a `POST` only when Druckling rejected it without rendering anything: - `429 rate_limited` is retried for every method, including `POST /v1/documents`. A rate-limited request rendered nothing. - `429 quota_exceeded` is never retried. - `408`, `5xx`, timeouts and connection errors are retried for `GET` and `DELETE` only. See [SDKs](/docs/sdks#retries) for backoff and configuration. ## Errors in the SDKs [#errors-in-the-sdks] Each SDK raises one error class per kind of failure, all under one base class, and they carry the same information as the JSON body: | What you get | TypeScript and Python | PHP | | --- | --- | --- | | Error code | `error.code` | `$e->errorCode` | | HTTP status | `error.status` | `$e->status` | | Offending field | `error.field` | `$e->field` | | All field errors | `error.errors` | `$e->errors` | | Failed document ID | `error.documentId` (TS), `error.document_id` (Python) | `$e->documentId` | | Request ID | `error.requestId` (TS), `error.request_id` (Python) | `$e->requestId` | `errors` combines `data.errors` and the `data.issues` of request validation errors, each as a field and a message. Classes by error: | Error | TypeScript and Python | PHP | | --- | --- | --- | | `400 BAD_REQUEST`, `schema_validation_failed`, `validation_failed` | `ValidationError` | `ValidationException` | | `unauthorized` | `AuthenticationError` | `AuthenticationException` | | `forbidden` | `PermissionDeniedError` | `PermissionDeniedException` | | `not_found` | `NotFoundError` | `NotFoundException` | | `conflict`, `invalid_state` | `ConflictError` | `ConflictException` | | `render_failed`, `render_timeout` | `RenderError` | `RenderException` | | `rate_limited` | `RateLimitError` | `RateLimitException` | | `quota_exceeded` | `QuotaExceededError`, a `RateLimitError` | `QuotaExceededException`, a `RateLimitException` | | `5xx` | `ServerError` | `ServerException` | | `payload_too_large` | `APIError` | `ApiException` | | No response | `APIConnectionError`, or `APITimeoutError` on timeout | `ConnectionException`, or `TimeoutException` on timeout | ```ts tab="TypeScript" import Druckling, { QuotaExceededError, ValidationError } from "@druckling/sdk"; const druckling = new Druckling(); try { await druckling.documents.create({ template: "invoice-standard", data }); } catch (error) { if (error instanceof ValidationError) { for (const issue of error.errors) console.error(`${issue.field}: ${issue.message}`); } else if (error instanceof QuotaExceededError) { console.error("Quota used up:", error.message); } else { throw error; } } ``` ```python tab="Python" from druckling import QuotaExceededError, Druckling, ValidationError client = Druckling() try: client.documents.create(template="invoice-standard", data=data) except ValidationError as error: for issue in error.errors: print(f"{issue.field}: {issue.message}") except QuotaExceededError as error: print("Quota used up:", error.message) ``` ```php tab="PHP" use Druckling\Exception\QuotaExceededException; use Druckling\Exception\ValidationException; use Druckling\Druckling; $druckling = new Druckling(); try { $druckling->documents->create(template: 'invoice-standard', data: $data); } catch (ValidationException $e) { foreach ($e->errors as $issue) { echo "{$issue->field}: {$issue->message}", PHP_EOL; } } catch (QuotaExceededException $e) { echo 'Quota used up: ', $e->getMessage(), PHP_EOL; } ``` The SDK pages cover each language's error classes in detail: [TypeScript](/docs/sdks/typescript), [Python](/docs/sdks/python), [PHP](/docs/sdks/php). ## Debugging [#debugging] - Every request that gets past the API key check shows up in **Developers › Logs**, with its status and duration. Requests rejected for a missing or invalid key don't; requests rejected by the per-key rate limit do, with status `429`. - Failed renders appear in **Documents** with their error, the offending field and the request body as received. - Each response has an `x-vercel-id` header that identifies the request. The SDKs expose it as the error's request ID. Include it when you contact support. # Plans and limits (/docs/concepts/plans-and-limits) > Druckling's plans and prices, what counts toward your document quota, rate limits, and the size limits that apply to every request. Every workspace is on one plan. The plan sets how many live documents you can render each month and each day, and a few features of the embedded editor. Everything else on this page, from rate limits to payload sizes, is the same on every plan. Renders with test keys are free and never limited by the quota. ## Plans [#plans] Prices are net, in euros, and billed per document, whatever its page count. | | Free | Starter | Pro | Business | | --- | --- | --- | --- | --- | | Monthly price | €0 | €9 | €29 | €99 | | Yearly price | – | €90 | €290 | €990 | | Live documents per month | 250 | 1,000 | 10,000 | 50,000 | | Live documents per day | 100 | 1,000 | 10,000 | 50,000 | | Test documents | Unlimited | Unlimited | Unlimited | Unlimited | | Pages per document | 50 | 100 | 200 | 500 | | File retention | 30 days | 30 days | 30 days | 30 days | | Signed download links | Up to 7 days | Up to 7 days | Up to 7 days | Up to 7 days | | Embedded editor without the "Powered by Druckling" mark | No | No | Yes | Yes | | Assistant in the embedded editor | No | No | Yes | Yes | Owners and admins choose and change the plan in **Settings › Billing**, billed monthly or yearly. A yearly plan costs ten times the monthly price. VAT is added at checkout where it applies, and you can enter your VAT ID for your invoices. Every plan can use the [embedded editor](/docs/guides/embedded-editor). On Free and Starter it shows a small "Powered by Druckling" mark, and the assistant isn't offered inside it even if a session asks for it. In embedded editors, Druck, the AI assistant, appears as a neutral "Assistant" without Druckling branding. ## What counts toward your quota [#what-counts-toward-your-quota] One live document that finishes rendering counts as one document, whether it's a PDF, a PNG or an XML e-invoice, and however many pages it has. That includes documents rendered through the API, the SDKs, the [MCP server](/docs/guides/mcp), [n8n](/docs/guides/n8n), each item of a [batch](/docs/guides/batches), and documents you retry from the dashboard in live mode. These don't count: - Anything rendered with a test key, or in **Test mode** in the dashboard. See [Test mode](/docs/concepts/test-mode). - Failed documents, whether they failed validation or rendering. - Previews and Test PDFs in the template editor. - Reading documents, downloading files, and creating or opening share links. A document counts toward the UTC day on which it finished rendering. ## When quotas reset [#when-quotas-reset] Both counters follow UTC, not your billing date: - The **daily** count resets at 00:00 UTC. - The **monthly** count resets at 00:00 UTC on the first day of each month. ## When you reach a quota [#when-you-reach-a-quota] Druckling checks the quota when it accepts a live render. Once the daily or monthly limit is used up, render requests fail with `429` until the counter resets or you upgrade. There are no overage charges. ```json title="429 Too Many Requests" { "defined": false, "code": "QUOTA_EXCEEDED", "status": 429, "message": "Monthly limit of 250 documents reached on the Free plan; it resets on 2026-11-01. Upgrade in Settings › Billing for a higher limit. Test keys are never limited.", "data": { "code": "quota_exceeded", "field": null, "scope": "monthly", "plan": "free", "used": 250, "limit": 250 } } ``` `data.scope` is `daily` or `monthly`, and `used` and `limit` are that counter's values. The daily limit is checked first. A live [batch](/docs/guides/batches) is checked as a whole: all of its items must fit in what's left today and this month, counting live documents that are still queued. If they don't, nothing is rendered, and `data` also has `requested` (the batch's items) and `reserved` (the documents already queued). The SDKs never retry `quota_exceeded`; they raise a quota error right away. To keep developing when your live quota runs out, switch to a test key. ## Rate limits [#rate-limits] ### Per API key [#per-api-key] Each API key can make 120 requests a minute. The minute starts with the key's first request; the 121st request within it gets `429`, and the count starts over when the minute is up. So steady traffic under 120 requests a minute is never blocked, however long it runs. The count is shared by all of Druckling's servers. Every authenticated request counts, on every endpoint and for test keys too: renders, polls of `GET /v1/documents/{id}`, list calls, and calls made through the [MCP server](/docs/guides/mcp) with that key. Each key has its own count. ```json title="429 Too Many Requests" { "defined": false, "code": "TOO_MANY_REQUESTS", "status": 429, "message": "Too many requests for this API key: the limit is 120 a minute. Retry in 18 s.", "data": { "code": "rate_limited", "field": null, "retryAfter": 18, "limit": 120 } } ``` The response says when the minute is up, in seconds, both in the `Retry-After` header and in `data.retryAfter`. The SDKs read the header and wait for you. To stay under the limit, follow documents with [webhooks](/docs/guides/webhooks) instead of polling, and render large jobs as one [batch](/docs/guides/batches) instead of one request per document. ### Other limits [#other-limits] A few more limits protect shared capacity. They're counted per server instance, so treat the numbers as approximate. | What | Limit | Response | | --- | --- | --- | | Creating [embedded editor sessions](/docs/guides/embedded-editor) | About 60 a minute per workspace | `429 rate_limited`, with the seconds to wait in `data.retryAfter` | | Requests from one embedded editor session (saves, previews) | About 600 a minute | `429 rate_limited`, with `data.retryAfter` | | Druck (AI assistant) turns | About 30 a minute per workspace, and about 10 a minute per embedded editor session | `429` with a `Retry-After` header | | Render capacity | When too many renders are waiting on one server | `429 rate_limited`, "The render engine is busy; retry shortly" | | Opening [share links](/docs/concepts/share-links) | About 120 a minute per IP address | `429` page with a `Retry-After` header | A render rejected because the engine is busy is recorded as a `failed` document with `error.code: "rate_limited"`. It produced no file and didn't count toward your quota, so sending the request again after a short pause is safe. An asynchronous render that hits this limit ends up `failed` the same way. When the REST API (`/v1`) knows how long you should wait, it sends a `Retry-After` header and the same number of seconds in `data.retryAfter`. ## Payload and render limits [#payload-and-render-limits] These limits apply on every plan. | Limit | Value | When exceeded | | --- | --- | --- | | Size of a document's `data` | 1,000,000 bytes as JSON | `413 payload_too_large` | | Items in any array of `data` | 10,000 | `413 payload_too_large`, with `field` set to the array's path | | Nesting depth of `data` | 32 levels | `422 validation_failed` | | `filename` | 200 characters | `400 BAD_REQUEST` | | Pages per document | Your plan's limit (50 to 500, see above) | `422 render_failed`, with the page count in `data.pages` and the limit in `data.limit` | | Typesetting time | 10 seconds | `504 render_timeout` | | Images per document | 20 distinct image URLs | Images beyond the 20th render as placeholders | | Size of one image | 5 MB, fetched within 4 seconds | The image renders as a placeholder | | Items per batch | 1 to 1,000 | `400 BAD_REQUEST` | | Size of a batch's `items` | 4 MB as JSON | `413 payload_too_large`, with `field: "items"` | | Active share links per document | 20 | `409 conflict` | | Share link lifetime | 1 to 30 days | `400 BAD_REQUEST` | | Webhook endpoints per workspace | 20 | `409 conflict` | | Embedded editor session lifetime | 60 seconds to 1 hour | `400 BAD_REQUEST` | Druckling checks the size, array and nesting limits of `data` when the document renders. A synchronous request gets the error as its response, and the document is recorded as `failed`. For an asynchronous request the error shows up on the `failed` document (for example `error.code: "payload_too_large"`), not on the request. Images are fetched while the document renders. Druckling only fetches public `https://` URLs that serve PNG, JPEG, GIF, SVG or WebP. An image that is missing, too large, too slow or of another type renders as a placeholder; the document still renders. ## Where to see your usage [#where-to-see-your-usage] **Settings › Usage** shows this month's and today's live documents against your limits, when the monthly count resets, and your plan's retention and link lifetimes. Test documents are listed as unlimited. To change plans, go to **Settings › Billing**. ## Next steps [#next-steps] Develop and test without using your quota. Every error code, and which ones are safe to retry. Render up to 1,000 documents with one request. # Share links (/docs/concepts/share-links) > Give anyone a public, expiring link to a rendered document, without an account or an API key. A share link is a public, unguessable URL for one rendered document. Whoever has it can open the file in a browser, with no Druckling account and no API key, until the link expires or you revoke it. Use share links to send an invoice to a customer, or to let someone outside your workspace review a contract. Every rendered document already has a signed download [`url`](/docs/concepts/documents#download-the-file). A share link is the better choice when a person, not your code, opens the file: | | Signed `url` | Share link | | --- | --- | --- | | Lifetime | Up to 7 days | 1 to 30 days, 7 by default | | Revocable | No | Yes, effective immediately | | Shown | On every read of the document | Once, when you create it | | File name | The link's path ends in the document ID | Served under the document's `filename` | Both stop working when the document's file is deleted at the end of [retention](/docs/concepts/documents#retention). The SDKs don't cover share links yet. Call the endpoints below directly with the same API key. ## Create a share link [#create-a-share-link] Send [`POST /v1/documents/{id}/share_links`](/docs/api-reference/share-links/create) with an optional `expires_in_days`, a whole number from 1 to 30 (default 7): ```bash curl https://druckling-nine.vercel.app/v1/documents/pdf_8Qw2kLm3nP0aB1cD/share_links \ -H "Authorization: Bearer $DRUCKLING_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "expires_in_days": 14 }' ``` The answer is `201 Created` with the link: ```json title="Response" { "id": "shl_4Fq9LmZ2xR8tKpWc", "object": "share_link", "document": "pdf_8Qw2kLm3nP0aB1cD", "url": "https://druckling-nine.vercel.app/s/k3J9vQ2xLm8RtY5wP1aZc7Nf0bHdx9Qa", "hint": "x9Qa", "status": "active", "expires_at": "2026-11-10T10:02:17.551Z", "revoked_at": null, "test_mode": true, "created_at": "2026-10-27T10:02:17.551Z" } ``` What to expect: - **Only rendered documents can be shared.** A document that is `queued`, `rendering` or `failed` answers `409` with code `invalid_state` ("Only rendered documents can be shared"). So does an expired one ("This document's file was deleted after the retention period"). - **The link never outlives the file.** `expires_at` is the earlier of `expires_in_days` from now and the document's own `expires_at`. Asking for 30 days on a document rendered 25 days ago gives a link that works for about 5 more days, without an error, so check `expires_at` in the response. - **Out-of-range lifetimes are rejected.** An `expires_in_days` below 1, above 30 or with a fraction fails with `400 BAD_REQUEST`. - **A document can have up to 20 active links.** The 21st answers `409` with code `conflict`. Revoke one first. - **Any API key works.** Both Render only and Full access keys can create, list and revoke share links. - **Links are free.** Creating and opening share links doesn't count toward your [plan's quota](/docs/concepts/plans-and-limits). ### The link is shown once [#the-link-is-shown-once] Druckling stores only a SHA-256 hash of each link, never the link itself, so `url` appears in the create response and nowhere else. Listing or revoking returns `url: null`. Store the link when you create it, or create a new one if you lose it. `hint` holds the link's last four characters, so you and your users can tell links apart (the dashboard shows it as `…x9Qa`). ## What visitors see [#what-visitors-see] Opening the link streams the file itself, with no Druckling page around it: - A PDF or PNG opens in the browser, like any file served inline. - An XML e-invoice is shown as XML, in a sandbox that keeps it from running anything. - Add `?download` to the link (for example `https://druckling-nine.vercel.app/s/k3J9…x9Qa?download`) to have the browser save the file instead of showing it. The file is served under the document's `filename`. Responses tell search engines not to index the file, tell browsers and proxies not to cache it, and send no referrer. Nothing in the response names your workspace. When a link can't be served, the visitor gets a short HTML page instead: | Status | Page | When | | --- | --- | --- | | `404` | Link not found | The link is incomplete or wrong, or it was deleted after it expired. | | `410` | This link was revoked | You revoked the link. | | `410` | This link has expired | The link reached its `expires_at`, or the document's file was deleted. | | `429` | Too many requests | Too many requests from one IP address, about 120 a minute. The response has a `Retry-After` header. | Expired links don't answer `410` forever. A daily cleanup deletes every link whose `expires_at` has passed, revoked links included. From then on the link answers `404`, and it no longer appears when you list the document's links. ## List a document's links [#list-a-documents-links] [`GET /v1/documents/{id}/share_links`](/docs/api-reference/share-links/list) returns every link of the document that hasn't been cleaned up yet, newest first: ```bash curl https://druckling-nine.vercel.app/v1/documents/pdf_8Qw2kLm3nP0aB1cD/share_links \ -H "Authorization: Bearer $DRUCKLING_API_KEY" ``` ```json title="Response" { "object": "list", "data": [ { "id": "shl_4Fq9LmZ2xR8tKpWc", "object": "share_link", "document": "pdf_8Qw2kLm3nP0aB1cD", "url": null, "hint": "x9Qa", "status": "active", "expires_at": "2026-11-10T10:02:17.551Z", "revoked_at": null, "test_mode": true, "created_at": "2026-10-27T10:02:17.551Z" } ] } ``` A link's `status` is worked out each time you read it: | `status` | Meaning | | --- | --- | | `active` | The link works. | | `expired` | The link reached its `expires_at`. | | `revoked` | You revoked it; `revoked_at` says when. | ## Revoke a link [#revoke-a-link] [`DELETE /v1/documents/{id}/share_links/{share_link_id}`](/docs/api-reference/share-links/revoke) stops the link immediately. The next visit gets `410`. ```bash curl -X DELETE https://druckling-nine.vercel.app/v1/documents/pdf_8Qw2kLm3nP0aB1cD/share_links/shl_4Fq9LmZ2xR8tKpWc \ -H "Authorization: Bearer $DRUCKLING_API_KEY" ``` The response is the link with `status: "revoked"` and `revoked_at` set. Revoking a link twice is fine and keeps the first `revoked_at`. An unknown link, or a link that belongs to another document, answers `404`. A revoked link can't be restored, and no link can be extended. Create a new link instead. ## In the dashboard [#in-the-dashboard] Open a rendered document in **Documents**. Under **Share links**, pick a lifetime in **Expires after** (1, 7, 14 or 30 days) and click **Create link**. Copy the link right away with **Copy**: like the API, the dashboard shows it only once. The list below shows each link's hint, status and expiry, with **Revoke** next to the active ones. ## Test mode [#test-mode] Share links work the same way for [test documents](/docs/concepts/test-mode). A link's `test_mode` matches the document it points to. ## Security [#security] Treat a share link like the file itself: - **Links can't be guessed.** The part after `/s/` is 32 random characters (192 bits), and Druckling keeps only its hash. - **Anyone with the link can open the file.** Send it only to the person who should see the document, over a channel you trust. Forwarding the link forwards access. - **Keep lifetimes short.** Pick the shortest expiry that works for the recipient. - **Revoke when in doubt.** Revoke a link as soon as it's no longer needed, or if it may have leaked. - **Keep links out of logs.** Refer to links by `id` or `hint` in your own logs and support tools, not by the full URL. ## Next steps [#next-steps] Formats, retention and signed download links. Every field of the share link endpoints. # Template strings (/docs/concepts/template-strings) > The syntax Druckling templates use to insert data, format numbers, amounts and dates with filters, and style text. Most texts in a template are template strings: paragraphs, headings, table cells and totals, barcode values and signer names. A template string is literal text with `{{bindings}}` that insert data, filters that format it, and a few formatting marks. ```text Hello **{{customer.name}}**, your total is {{totals.amount | money}}. Due {{invoice.due_date | date:"[day].[month].[year]"}} · [Pay online](https://pay.example.com) ``` With the `invoice-standard` sample data, this prints "Hello **Northwind Ltd.**, your total is $10,692.00." on the first line and "Due 22.11.2026 · Pay online" on the second, with "Pay online" as a link. ## Bindings [#bindings] `{{path}}` inserts the value at a dotted path of the payload. Spaces inside the braces are fine: `{{ customer.name }}` works too. - A path is made of names with letters, digits and underscores, separated by dots. A name can't start with a digit, so a binding can't index into a list; print list items with a [table](#conditional-blocks-and-repeating-rows). - Every binding must point to a [declared variable](/docs/concepts/variables). Otherwise the editor shows an error and you can't publish. - In a table cell, bind the row through the table's row alias, for example `{{item.qty}}`. Data is always inserted as plain text: | Value in the payload | Prints as | | --- | --- | | `"Northwind Ltd."` | `Northwind Ltd.` | | `4800`, `4800.5` | `4800`, `4800.5` (use a [filter](#filters) to format numbers) | | `true`, `false` | `true`, `false` | | `["a", "b"]` | `a, b` | | an object | nothing (bind one of its fields) | | a string with a line break (`"12 Pier St\nLeeds"`) | two lines | ### Missing values [#missing-values] A missing key or `null` prints nothing, with or without a filter, and doesn't fail the render. If the variable is required, the request fails [validation](/docs/concepts/variables#validation-on-every-render) before anything renders. To print a fallback, use the [`default`](#default) filter. ## Filters [#filters] A filter formats the bound value: `{{path | filter}}`, or `{{path | filter:"argument"}}` for filters that take an argument. The quotes around the argument are optional. Each binding takes at most one filter. Chaining, as in `{{name | upper | default:"n/a"}}`, is a validation error, and so is an unknown filter name. | Filter | Argument | What it does | | --- | --- | --- | | [`money`](#money) | Currency code, such as `"EUR"` (default: the template's currency) | Formats a number as an amount with a currency symbol. | | [`date`](#date) | Date pattern (default: depends on the language) | Formats a `YYYY-MM-DD` date. | | [`number`](#number) | Decimals: `"2"` or a range such as `"0-2"` (default: `0`) | Formats a number with grouping and decimals. | | [`percent`](#percent) | Decimals (default: `0`) | Multiplies by 100 and adds `%`. | | [`upper`](#upper-and-lower) | | Converts to uppercase. | | [`lower`](#upper-and-lower) | | Converts to lowercase. | | [`default`](#default) | Fallback text | Prints the fallback when the value is missing, `null` or empty. | Filters that expect a number also accept numeric strings such as `"12.50"`. A value they can't format prints unchanged, so `{{status | money}}` with `"n/a"` prints `n/a`. The examples below were produced by the rendering engine. Unless a row says otherwise, the language is English (`en`) and the template's currency is USD. "nbsp" stands for a no-break space and "nnbsp" for a narrow no-break space. ### money [#money] Prints two decimals (none for JPY and KRW), the language's separators and the currency's symbol. | Template string | Value | Language, currency | Output | | --- | --- | --- | --- | | `{{amount \| money}}` | `4800` | en, USD | `$4,800.00` | | `{{amount \| money}}` | `-12.5` | en, USD | `-$12.50` | | `{{amount \| money:"EUR"}}` | `4800` | en | `€4,800.00` | | `{{amount \| money:"GBP"}}` | `4800` | en | `£4,800.00` | | `{{amount \| money:"CHF"}}` | `4800` | en | `CHF 4,800.00` (nbsp) | | `{{amount \| money:"JPY"}}` | `4800` | en | `¥4,800` | | `{{amount \| money}}` | `4800` | de, EUR | `4.800,00 €` (nbsp) | | `{{amount \| money}}` | `4800` | fr, EUR | `4 800,00 €` (nnbsp, nbsp) | | `{{amount \| money:"PLN"}}` | `1234.567` | pl | `1.234,57 zł` (nbsp) | | `{{amount \| money:"XYZ"}}` | `4800` | en | `XYZ 4,800.00` (nbsp) | - Without an argument, `money` uses the currency set in the editor under **Document › Output › Currency** (USD by default). In an e-invoice template it uses the payload's `invoice.currency`. - Languages with a decimal comma put the symbol after the amount; the others put it before. - Symbols are built in for USD ($), EUR (€), GBP (£), JPY and CNY (¥), INR (₹), KRW (₩), CAD (CA$), AUD (A$), NZD (NZ$), BRL (R$), MXN (MX$), CHF (CHF), SEK, NOK and DKK (kr), PLN (zł), CZK (Kč), TRY (₺) and ZAR (R). Any other code prints as is, so write codes in uppercase. ### date [#date] Formats a value that starts with `YYYY-MM-DD`. Anything after the date, such as a time, is ignored. | Template string | Value | Language | Output | | --- | --- | --- | --- | | `{{due \| date}}` | `"2026-11-22"` | en | `Nov 22, 2026` | | `{{due \| date}}` | `"2026-11-22"` | de, pl and most others | `22.11.2026` | | `{{due \| date}}` | `"2026-11-22"` | fr, es, it, pt | `22/11/2026` | | `{{due \| date}}` | `"2026-11-22"` | nl | `22-11-2026` | | `{{due \| date}}` | `"2026-11-22T14:30:00Z"` | en | `Nov 22, 2026` | | `{{due \| date:"[day].[month].[year]"}}` | `"2026-11-22"` | any | `22.11.2026` | | `{{due \| date:"[month repr:long] [day], [year]"}}` | `"2026-11-22"` | any | `November 22, 2026` | | `{{due \| date:"[weekday], [day padding:none] [month repr:short] [year]"}}` | `"2026-11-22"` | any | `Sunday, 22 Nov 2026` | | `{{due \| date:"[day padding:none]. [month padding:none]. [year]"}}` | `"2026-03-05"` | any | `5. 3. 2026` | | `{{due \| date:"[year repr:last_two]"}}` | `"2026-11-22"` | any | `26` | | `{{due \| date}}` | `"soon"` | any | `soon` | Patterns use [Typst's date format syntax](https://typst.app/docs/reference/foundations/datetime/): components such as `[day]`, `[month]`, `[year]` and `[weekday]` in square brackets, with modifiers such as `padding:none` or `repr:long`. Text outside the brackets prints as written. - Month and weekday names are always English, whatever the render language: `[month repr:long]` prints `November` in a German document too. For other languages, use numeric patterns or the default. - An unknown component, such as `[foo]`, makes the render fail with `render_failed`. Publishing renders the sample data, so it catches this as long as the sample data has a date in that field. The schema only checks that a date starts with `YYYY-MM-DD`. A value such as `2026-02-31` passes validation, but formatting it with `date` fails the render with `render_failed` ("date is invalid"). Validate dates in your own code before you send them. ### number [#number] | Template string | Value | Language | Output | | --- | --- | --- | --- | | `{{x \| number}}` | `1234.5` | en | `1,235` | | `{{x \| number:"2"}}` | `1234.5` | en | `1,234.50` | | `{{x \| number:"2"}}` | `1234.5` | de | `1.234,50` | | `{{x \| number:"2"}}` | `1234.5` | fr | `1 234,50` (nnbsp) | | `{{x \| number:"0-2"}}` | `1234.5` | en | `1,234.5` | | `{{x \| number:"0-2"}}` | `19` | en | `19` | | `{{x \| number:"0-2"}}` | `5.5` | de | `5,5` | | `{{x \| number:"1-2"}}` | `5.555` | en | `5.56` | | `{{x \| number:"1"}}` | `-1234.5` | en | `-1,234.5` | | `{{x \| number}}` | `2.5` | en | `3` | - Without an argument, `number` rounds to a whole number. Halves round away from zero. - `"2"` prints exactly two decimals. A range such as `"0-2"` prints up to two and drops trailing zeros, which suits VAT rates like 19 and 5.5. - The argument is a single digit (0 to 9) or a range of two digits. Anything else, such as `"10"`, counts as no argument. ### percent [#percent] | Template string | Value | Language | Output | | --- | --- | --- | --- | | `{{rate \| percent}}` | `0.19` | en | `19%` | | `{{rate \| percent:"1"}}` | `0.055` | en | `5.5%` | | `{{rate \| percent:"1"}}` | `0.055` | de | `5,5%` | | `{{rate \| percent}}` | `19` | en | `1,900%` | `percent` expects a fraction and multiplies it by 100. If your data already holds percentages, such as a VAT rate of `19`, use `{{rate | number:"0-2"}}%` instead. ### upper and lower [#upper-and-lower] | Template string | Value | Output | | --- | --- | --- | | `{{name \| upper}}` | `"Ada Lovelace"` | `ADA LOVELACE` | | `{{name \| upper}}` | `"straße"` | `STRASSE` | | `{{code \| lower}}` | `"ADA"` | `ada` | ### default [#default] | Template string | Value | Output | | --- | --- | --- | | `{{po \| default:"n/a"}}` | missing or `null` | `n/a` | | `{{po \| default:"n/a"}}` | `""` | `n/a` | | `{{po \| default:"n/a"}}` | `0` | `0` | | `{{po \| default:"n/a"}}` | `false` | `false` | | `{{po \| default:"n/a"}}` | `"PO-77"` | `PO-77` | The fallback is plain text. It can't contain `|` or `}}`. ## Language and number formats [#language-and-number-formats] The render's [`language`](/docs/guides/languages), or the template's default language when a request names none, decides the separators and the default date format: | Languages | Numbers | Default date | | --- | --- | --- | | `en` | `1,234.50` | `Nov 22, 2026` | | `fr` | `1 234,50` (nnbsp) | `22/11/2026` | | `es`, `it`, `pt` | `1.234,50` | `22/11/2026` | | `nl` | `1.234,50` | `22-11-2026` | | `bg`, `ca`, `cs`, `da`, `de`, `el`, `et`, `fi`, `hr`, `hu`, `is`, `lb`, `lt`, `lv`, `nb`, `no`, `pl`, `ro`, `ru`, `sk`, `sl`, `sv`, `tr`, `uk` | `1.234,50` | `22.11.2026` | | Any other code, such as `ga` (Irish) or `mt` (Maltese) | `1,234.50` | `22.11.2026` | The language changes how an amount is formatted, not its currency: `money` without an argument always uses the template's currency. ## Formatting marks [#formatting-marks] | Write | Result | | --- | --- | | `**bold**` | **bold** | | `*italic*` | *italic* | | `**bold *and italic***` | **bold *and italic*** | | `[label](https://example.com)` | A link. The URL must start with `https://`, `http://` or `mailto:`. | | A line break | A line break in the PDF. | Marks apply to bindings inside them: `**{{customer.name}}**` prints the name in bold, and `[Invoice {{invoice.number}}](https://example.com/pay)` makes it part of the link text. - A link's URL is used exactly as written, bindings included: `[Pay](https://pay.example.com/{{invoice.number}})` links to a URL that literally contains `{{invoice.number}}`. Links can't be built from data. A [QR code](/docs/concepts/variables#images-barcodes-and-qr-codes) can. - If the URL doesn't start with one of the allowed schemes, the whole `[label](url)` prints as text. - An unclosed `**` or `*` is a validation error. A lone asterisk, as in `Prices marked * include VAT`, opens italic text, so escape it: `Prices marked \* include VAT`. ## Escaping [#escaping] A backslash prints the next character literally: | Write | Prints | | --- | --- | | `\{{name}}` | `{{name}}` | | `\*` | `*` | | `\[` | `[` | | `\\` | `\` | Single braces, and `}}` without an opening `{{`, need no escaping. When you send a template string inside JSON, for example through the [MCP server](/docs/guides/mcp), escape the backslash itself: `"\\{{name}}"`. Data never needs escaping. A customer name such as `**ACME** {{x}}` prints exactly like that, without bold and without a binding. ## Where template strings work [#where-template-strings-work] | Field | Template string | Notes | | --- | --- | --- | | Text and heading content | Yes | | | Table cell | Yes | The row alias is in scope: `{{item.qty}}`. | | Table totals value | Yes | Binds top-level fields such as `{{totals.amount \| money}}`, not the row alias. | | QR / Barcode value | Yes | Evaluated to plain text before the code is drawn: marks are dropped, `money` prints the currency code (`USD 4,800.00`) and `date` leaves the value unformatted. | | Signature signer | Yes | For example `{{landlord.name}}`. | | Table column header, totals label, empty-table text | No | Plain text, printed as written. | | Signature label, chart title, image alt text | No | Plain text. | | Document title, watermark | No | Plain text. | | Page number format | No | Takes the placeholders `{page}` and `{total}`. | | Image source | No | Choose a fixed URL or an image variable on the block. | | Batch `filename_pattern` | Partly | Supports `{{path}}` with the `upper`, `lower` and `default` filters; other filters insert the raw value. See [Batches](/docs/guides/batches). | The `filename` of a single [`POST /v1/documents`](/docs/api-reference/documents/create) request is used as written, without bindings. ## Conditional blocks and repeating rows [#conditional-blocks-and-repeating-rows] Template strings have no `if` or loop syntax. Blocks do the job instead. **Repeating rows.** A Table block repeats one row per item of a list variable (its `each`, such as `line_items`) and names the current row with an alias (`item` by default). Tables can sort rows by a field, hide themselves or show a text when the list is empty, and end with totals rows. **Conditional blocks.** Any block can have a visibility condition, set under **Visibility** in the block's settings. The block prints only when the condition holds. The `invoice-standard` starter uses one to print the payment QR code only when `payment.url` is not empty. | Condition | API name | True when | | --- | --- | --- | | is not empty | `notEmpty` | The value is present and, for text, lists and objects, not empty. | | exists | `exists` | The value is present and not `null`. | | is true / non-zero | `truthy` | The value isn't `null`, `false`, `""` or `0`, and isn't an empty list or object. | | equals | `eq` | The value equals the given value, compared as text, so `3` equals `"3"`. | | does not equal | `neq` | The opposite of `eq`. | | is greater than, is at least, is less than, is at most | `gt`, `gte`, `lt`, `lte` | Both sides are numbers (or numeric strings) and the comparison holds. Otherwise false. | A block has one condition, on a payload field such as `payment.url`; it can't test a field of a table row. To require two conditions, put the block in a Box with its own condition: the box's condition and the block's both have to hold. ## Safety [#safety] Template strings can't inject code into the rendering engine. The literal text of a template reaches the Typst engine only as escaped string literals, and payload data never becomes part of the template source: it's read from a separate JSON file and printed as plain text. A customer name such as `#set page(paper: "a7")` prints as those characters and changes nothing about the layout. Declare the fields your bindings read. Render one template in several languages. # Templates (/docs/concepts/templates) > What a Druckling template contains, how its draft becomes immutable published versions, and how to read templates through the API. A template is a document layout plus the data contract it expects. You design it in the visual editor, publish it, and then render documents from it by sending its slug and a JSON payload to [`POST /v1/documents`](/docs/api-reference/documents/create). ## What a template contains [#what-a-template-contains] Every template is one document with these parts: - **Page setup**: paper size and orientation, margins in millimeters, a header and footer that repeat on every page, an optional first-page header (for letterheads) and an optional text watermark. - **Document settings**: title and author (written to the PDF metadata), fonts, base text size, line spacing, default language, hyphenation, justification, text and accent colors, the currency the `money` filter uses, the PDF standard and e-invoicing. - **Variables**: the fields the payload can or must contain. They define the template's [JSON Schema](/docs/concepts/variables). - **Sample data**: an example payload, used for previews and checked when you publish. - **Blocks**: the content, in order. - **Translations**: texts for languages other than the default one. See [Languages](/docs/guides/languages). ### Blocks [#blocks] | Block | What it does | | --- | --- | | Text | A paragraph with [template strings](/docs/concepts/template-strings): bound values, bold, italic and links. | | Heading | A level 1, 2 or 3 heading. | | Table | Repeats one row per item of a list variable, with a repeating header, page-break rules, sorting and optional totals rows. | | Image | An image from a fixed https URL or from an image variable. Shows a placeholder box when there's no image. | | Chart | A bar or line chart over a list variable. | | QR / Barcode | A QR code, Code 128, EAN-13 or Data Matrix code whose value is a template string. | | Signature | A signature line with a label, an optional signer name and an optional date line. | | Page no. | A page counter such as `Page {page} of {total}`, usually in the footer. | | Divider | A horizontal rule. | | Spacer | Vertical space, in points. | | Page break | Starts a new page. | | Box | A container with an optional fill and border, for notes and callouts. | | Columns | Up to six side-by-side columns, each holding its own blocks. | Every block also has style settings (alignment, size, weight, italic, color, font, space above and below, keep together on one page) and an optional visibility condition that shows it only when the payload meets it. See [Conditional blocks](/docs/concepts/template-strings#conditional-blocks-and-repeating-rows). ## Slugs [#slugs] API requests identify a template by its slug, for example `invoice-standard`. Druckling derives the slug from the name when you create the template: it lowercases the name, removes accents, turns everything other than letters and digits into dashes and keeps at most 56 characters. `Invoice — Standard (EU)` becomes `invoice-standard-eu`. If the slug is taken, Druckling appends `-2`, `-3` and so on. A slug is 2 to 63 characters long, uses lowercase letters, digits and dashes, starts with a letter or digit, and is unique within the workspace. Test and live API keys see the same templates, so a slug works with both `dr_test_…` and `dr_live_…` keys. ## Kinds [#kinds] Each template has a kind: `invoice`, `certificate`, `report`, `ticket`, `agreement`, `packing` or `custom`. A template made from a starter takes the starter's kind; a blank template is `custom`. The kind only labels the template in the dashboard. It doesn't change how it renders, and the API doesn't return it. ## Starters [#starters] Starters are ready-made templates with variables and sample data. Create a template from one in **Templates › New template**, which also offers a blank A4 page, a template built by Druck, the AI assistant, from an image or sketch, and **Import from PDF**. | Slug | Name | What it is | In new workspaces | | --- | --- | --- | --- | | `invoice-standard` | Invoice | A4 invoice with line items, totals and a payment QR code. | Created and published as version 1 | | `course-certificate` | Course certificate | Landscape A4 certificate with a signature line and a verification QR code. | Created as a draft | | `quarterly-report` | Quarterly report | Summary, revenue bar chart and KPI table. | Created as a draft | | `event-ticket` | Event ticket | Landscape A6 ticket with a scannable QR code. | Created as a draft | | `rental-agreement` | Rental agreement | Multi-page contract with clauses and two signature lines. | Created as a draft | | `packing-slip` | Packing slip | A5 slip with order items and a Code 128 barcode. | Created as a draft | | `rechnung-zugferd` | Rechnung (ZUGFeRD) | German EN 16931 e-invoice (ZUGFeRD / Factur-X, PDF/A-3b) with the §14 UStG details and a GiroCode. | Not created; add it from **New template** | | `facture-factur-x` | Facture (Factur-X) | French EN 16931 e-invoice (Factur-X, PDF/A-3b) with the mandatory mentions. | Not created; add it from **New template** | A new workspace starts with the first six. Only `invoice-standard` is published, so it's the only one you can render right away; publish the others before you render them. The e-invoice starters are covered in [E-invoicing](/docs/guides/e-invoicing). ## Editing templates [#editing-templates] ### Visual editor [#visual-editor] Open a template under **Templates** and click **Open editor**. The left panel holds the **Blocks** palette, the **Layers** tree and the **Data** tab with variables and sample data. The right panel edits the selected **Block**, the **Page** and the **Document**. The canvas is rendered by the same Typst engine as the API, with your sample data, and a switch above it shows either the variable names or the sample values. **Test PDF** renders the draft with its sample data into a PDF you can download. It doesn't create a document or count toward your plan. ### Druck [#druck] The editor comes with Druck, the AI assistant. You can ask Druck for changes in plain language. Druck reads the draft, its variables and sample data, and it can: - add, restyle, move and remove blocks, declare variables and fill in sample data, - lay out the draft with the real engine to answer questions such as "will 40 line items fit on two pages?", - check a payload against the template's schema, - translate the template into another language, - read this template's recent renders to explain a failure, - rebuild a layout from an attached image, sketch or PDF. Druck proposes changes as a card that you **Apply** or **Discard**. Nothing changes until you apply it, and applied changes land in the draft like your own edits. ### Other ways to edit [#other-ways-to-edit] - An AI agent can create, edit, preview and publish templates through the hosted [MCP server](/docs/guides/mcp) with a **Full access** API key. - Your own users can edit a template inside your product with the [embedded editor](/docs/guides/embedded-editor). The `/v1` REST API reads templates but doesn't edit them. ## Drafts, versions and publishing [#drafts-versions-and-publishing] A template has one editable **draft** and any number of published **versions**. Renders always use a version, never the draft. ### The draft [#the-draft] The editor saves the draft continuously while you work. Each save applies a set of edit operations to a numbered revision of the draft and increments it. If someone else saved the draft since the revision your change was based on, the save is rejected with `stale_revision` (409). The editor handles this for you: it loads the newer draft and reapplies your changes on top. An agent working through the MCP server gets the error and has to re-read the draft before it retries. ### Publishing [#publishing] Click **Publish** in the editor (**Publish changes** once a version exists), optionally describe what changed, and confirm. The note can be up to 500 characters and shows in the template's **Versions** tab. Publishing creates the next version number (1, 2, 3, …) as an immutable snapshot of the document, its JSON Schema and its required fields. Before it does, Druckling checks the draft: 1. The draft has no validation errors. Warnings don't block publishing; see [Validation issues](#validation-issues). 2. The sample data matches the template's variables. 3. The draft renders with the sample data, including the checks of its PDF standard. If a check fails, nothing is published and you get the reason: `validation_failed` (422) for the first two, `render_failed` (422) for the third, and `stale_revision` (409) if the draft changed while publishing. A template's `status` is `draft` until it's published for the first time and `published` from then on, even while the draft has newer changes. `latest_version` is the newest version number, or `null` before the first publish. ### Which version a render uses [#which-version-a-render-uses] [`POST /v1/documents`](/docs/api-reference/documents/create) and [`POST /v1/batches`](/docs/api-reference/batches/create) take an optional `version`: a version number, or `"latest"` (the default). - `"latest"` resolves when the request arrives, and the document records the number it used in `version`. An asynchronous render keeps that number even if you publish again before it runs. - Editing the draft never changes what renders produce. Only publishing does, and only for requests that use `"latest"`. - Pinned versions keep working after you publish newer ones. ```bash tab="cURL" curl https://druckling-nine.vercel.app/v1/documents \ -H "Authorization: Bearer $DRUCKLING_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "template": "invoice-standard", "version": 1, "data": { "invoice": { "number": "INV-2041", "due_date": "2026-11-22" }, "customer": { "name": "Northwind Ltd.", "address": "12 Pier St, Leeds" }, "line_items": [ { "description": "Design system audit", "qty": 12, "rate": 180, "amount": 2160 } ], "totals": { "subtotal": 2160, "tax": 172.8, "amount": 2332.8 } } }' ``` ```ts tab="TypeScript" import Druckling from "@druckling/sdk"; const druckling = new Druckling(); const document = await druckling.documents.create({ template: "invoice-standard", version: 1, data: { invoice: { number: "INV-2041", due_date: "2026-11-22" }, customer: { name: "Northwind Ltd.", address: "12 Pier St, Leeds" }, line_items: [{ description: "Design system audit", qty: 12, rate: 180, amount: 2160 }], totals: { subtotal: 2160, tax: 172.8, amount: 2332.8 }, }, }); ``` ```python tab="Python" from druckling import Druckling client = Druckling() document = client.documents.create( template="invoice-standard", version=1, data={ "invoice": {"number": "INV-2041", "due_date": "2026-11-22"}, "customer": {"name": "Northwind Ltd.", "address": "12 Pier St, Leeds"}, "line_items": [{"description": "Design system audit", "qty": 12, "rate": 180, "amount": 2160}], "totals": {"subtotal": 2160, "tax": 172.8, "amount": 2332.8}, }, ) ``` ```php tab="PHP" documents->create( template: 'invoice-standard', data: [ 'invoice' => ['number' => 'INV-2041', 'due_date' => '2026-11-22'], 'customer' => ['name' => 'Northwind Ltd.', 'address' => '12 Pier St, Leeds'], 'line_items' => [ ['description' => 'Design system audit', 'qty' => 12, 'rate' => 180, 'amount' => 2160], ], 'totals' => ['subtotal' => 2160, 'tax' => 172.8, 'amount' => 2332.8], ], version: 1, ); ``` Pin the version your integration was built against. You can then publish freely, and move the pin when your code sends what the new version expects, for example a field that became required. Rendering a template that was never published fails with 404 `not_found` and `field: "template"`, with the message `Template quarterly-report has no published version yet; publish it first`. A version number that doesn't exist fails with 404 `not_found` and `field: "version"`, for example `Template invoice-standard has no version 7`. See [Errors](/docs/concepts/errors). ## Validation issues [#validation-issues] The editor checks the draft as you edit and lists the problems in the status menu above the canvas. Errors block publishing; warnings don't. Errors include: - a binding to a variable that isn't declared, such as `{{customer.phone}}`, - template string syntax: an unclosed `{{`, an unknown filter, more than one filter in a binding, or an unclosed `**` or `*`, - a table or chart over a variable that isn't a declared list, or an image bound to an undeclared variable, - a visibility condition on an undeclared variable, or a comparison without a value, - a variable declared twice, or two blocks with the same id, - the rules of the chosen PDF standard, such as alt text on images for PDF/UA-1 and PDF/A-3a (see [Accessible PDFs](/docs/guides/accessible-pdfs)), - e-invoicing settings that don't fit together, such as Factur-X without PDF/A-3 (see [E-invoicing](/docs/guides/e-invoicing)), - translations that are too long or contain broken bindings. Warnings include a binding to a whole object or list instead of one of its fields, a sort field or chart axis that isn't declared on the list, and texts that aren't translated yet (they print in the default language). ## Template settings [#template-settings] Page and document settings are part of the draft, so a change takes effect for renders when you publish it. | Setting | Where | Options | | --- | --- | --- | | Paper | **Page › Paper** | A4, A5, A6, Letter, Legal or a 4 × 6 in label, portrait or landscape. | | Margins, header and footer | **Page** | Margins in millimeters; header, footer and first-page header blocks; watermark. | | PDF standard | **Document › Output** | Standard PDF, PDF/A-2b, PDF/A-3b, PDF/A-3a or PDF/UA-1, one per template. See [Accessible PDFs](/docs/guides/accessible-pdfs). | | E-invoice (EN 16931) | **Document › Output** | Factur-X / ZUGFeRD, XRechnung or Peppol BIS. See [E-invoicing](/docs/guides/e-invoicing). | | Currency | **Document › Output** | The default currency of the `money` filter (USD unless you change it). See [Template strings](/docs/concepts/template-strings#money). | | Language | **Document › Typography** and the language switcher above the canvas | A default language plus up to 30 more. See [Languages](/docs/guides/languages). | ## Duplicating a template [#duplicating-a-template] **Duplicate** on the template page copies the current draft into a new template named after the original with `(copy)` appended, with the slug `-copy` (or `-copy-2`, …). The copy starts as an unpublished draft with no versions, so publish it before you render it. Documents rendered from the original stay with the original. ## Templates in the API [#templates-in-the-api] Two read-only endpoints describe your templates. Both need the `templates:read` permission, which **Full access** keys have. A **Render only** key gets 403 `forbidden`. Create keys in **Developers › API keys**; see [Authentication](/docs/authentication). - [`GET /v1/templates`](/docs/api-reference/templates/list) lists every template in the workspace, drafts included, most recently changed first. The list isn't paginated. - [`GET /v1/templates/{slug}`](/docs/api-reference/templates/get) returns one template with its `json_schema` and `sample_data`. `required_fields`, `language`, `languages`, `json_schema` and `sample_data` describe the latest published version, or the draft for a template that was never published. Unpublished draft changes don't show up until you publish. ```bash tab="cURL" curl https://druckling-nine.vercel.app/v1/templates/invoice-standard \ -H "Authorization: Bearer $DRUCKLING_API_KEY" ``` ```ts tab="TypeScript" import Druckling from "@druckling/sdk"; const druckling = new Druckling(); const template = await druckling.templates.get("invoice-standard"); console.log(template.latest_version, template.required_fields); ``` ```python tab="Python" from druckling import Druckling client = Druckling() template = client.templates.get("invoice-standard") print(template.latest_version, template.required_fields) ``` ```php tab="PHP" templates->get('invoice-standard'); echo $template->latestVersion, ' ', implode(', ', $template->requiredFields), PHP_EOL; ``` The response, with `json_schema` and `sample_data` shortened (the full schema is on [Variables and schema](/docs/concepts/variables#the-derived-json-schema)): ```json title="200 OK" { "id": "tpl_3Hk9QmZ1xT7pLw2V", "object": "template", "slug": "invoice-standard", "name": "Invoice", "status": "published", "latest_version": 1, "required_fields": [ "invoice.number", "invoice.due_date", "customer.name", "customer.address", "line_items[].description", "line_items[].qty", "line_items[].rate", "line_items[].amount", "totals.subtotal", "totals.amount" ], "language": "en", "languages": ["en"], "updated_at": "2026-10-27T09:12:44.512Z", "json_schema": { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "customer": { "type": "object", "properties": { "name": { "type": "string" }, "address": { "type": "string" } }, "required": ["name", "address"] } }, "required": ["invoice", "customer", "line_items", "totals"] }, "sample_data": { "customer": { "name": "Northwind Ltd.", "address": "12 Pier St, Leeds" } } } ``` `required_fields` lists the required leaf fields. Fields of list items appear with `[]`, as in `line_items[].qty`: each item must have them. Declare the data a template expects and validate payloads. Bind values, format them with filters and style text. Render templates synchronously or asynchronously. # Test mode (/docs/concepts/test-mode) > Build against test keys that render real documents for free and keep their data apart from live mode, then switch keys to go live. Every Druckling workspace has two modes, live and test. Test mode lets you build and check an integration with real renders that cost nothing and never mix with your production data. The API key decides the mode: `dr_test_…` keys work in test mode, `dr_live_…` keys in live mode. ## What test mode changes [#what-test-mode-changes] - **Renders are free.** Test renders never count toward your plan's daily or monthly documents, and quota checks are skipped, so a test request never fails with `429 quota_exceeded`. That includes [batches](/docs/guides/batches): a test batch doesn't have to fit in the documents you have left. - **The output doesn't change.** Test documents are rendered exactly like live ones: no watermark, the same template version, the same PDF/A or PDF/UA settings and the same e-invoice XML. Files are kept for the same 30 days, and signed links work for the same 7 days. - **Other limits still apply.** Rate limits, request size limits and payload validation work the same in both modes. See [Plans and limits](/docs/concepts/plans-and-limits). ## How the mode is chosen [#how-the-mode-is-chosen] ### In the API [#in-the-api] The key's prefix is the only thing that decides the mode. There's no header or parameter to switch it, so the same code runs in test and live mode: only the key changes. You create keys of either mode under **Developers › API keys**; see [Authentication](/docs/authentication). The SDKs tell you which mode a client is in: `druckling.mode` in TypeScript and `client.mode` in Python return `"test"` or `"live"` based on the key. ### In the dashboard [#in-the-dashboard] The **Test mode** switch at the bottom of the sidebar chooses which data the dashboard shows. While it's on, a colored line runs along the top of the page, and documents, batches, request logs and the numbers on **Overview** and **Metrics** come from test mode only. Batches you start from the dashboard run in test mode too. The switch is saved in a cookie (`dr_mode`) in your browser. It doesn't affect API requests, your API keys or what other members of your team see. The plan meter in the sidebar always shows live usage, because test renders don't count. ## What's kept apart [#whats-kept-apart] | Resource | How the mode applies | | --- | --- | | [Documents](/docs/concepts/documents) | Created in the key's mode, with `test_mode` set. Lists show only the key's mode. | | [Batches](/docs/guides/batches) | Created in the key's mode, with `test_mode` set. Their documents are in the same mode. | | [Share links](/docs/concepts/share-links) | Take the mode of their document, shown in `test_mode`. | | [Webhook endpoints](/docs/guides/webhooks) | Each endpoint has one mode, chosen when it's created and fixed after that. A test endpoint receives only test events, and every event has `test_mode` set. An API key creates endpoints in its own mode and only sees those; the dashboard lists both modes. | | [Embedded editor sessions](/docs/guides/embedded-editor) | Created in the key's mode, with `test_mode` set. A key can only revoke sessions of its own mode. | | Request logs | **Developers › Logs** shows the requests of the dashboard's current mode. | | Usage | Only live renders count toward your plan. | These are shared between the modes: templates and their published versions, API keys (the list shows both, with a mode badge), embed settings such as allowed origins, team members, billing and workspace settings. There's one set of templates per workspace. Publishing a new version changes what `latest` renders in both modes, whether you publish in the dashboard, through an embedded editor session created with a test key, or through the MCP server with a test key. To try template changes without touching live renders, pin `version` in your live requests. A key only ever sees objects of its own mode. Lists leave the other mode out, and an ID from the other mode answers `404`, as if it didn't exist: documents, batches, share links, webhook endpoints and embedded editor sessions alike. ## Go live [#go-live] ### Build with a test key [#build-with-a-test-key] Create a **Test** key and use it in local development, CI and staging. Choose **Render only** unless the integration also manages webhooks, reads templates or creates editor sessions. ### Test webhooks with a test endpoint [#test-webhooks-with-a-test-endpoint] Add a webhook endpoint in test mode that points at your staging or development URL. It receives only test events, so it never sees production documents. ### Switch to a live key [#switch-to-a-live-key] Create a **Live** key with the permission your production service needs and put it in your production environment. Nothing else in your code changes. If you use webhooks, add a live endpoint for your production URL: it has its own signing secret. ### Check the mode where it matters [#check-the-mode-where-it-matters] Keep live keys out of development and staging. In webhook handlers and anywhere you act on documents by ID, check `test_mode` so test data can't trigger production work, such as emailing an invoice to a customer. ## E-invoices in test mode [#e-invoices-in-test-mode] [E-invoices](/docs/guides/e-invoicing) render and validate exactly the same way in both modes. A test Factur-X invoice is the same PDF/A-3 with the same embedded XML as a live one, and the EN 16931, XRechnung and Peppol rules are checked just as strictly. That makes test mode a reliable way to check your invoice data before you go live. Nothing in the PDF or XML marks a test invoice as a test. Treat test invoices as samples, and don't send them to customers or into accounting or e-invoicing networks. # Variables and schema (/docs/concepts/variables) > Declare the data a template expects, see the JSON Schema Druckling derives from it, and validate payloads before you render. Variables are a template's data contract. You declare each field the template reads, with a path and a type. Druckling turns the list into a JSON Schema, validates every render request against it, and returns it from the API so you can validate on your side too. ## How data binds to a template [#how-data-binds-to-a-template] The `data` you send to [`POST /v1/documents`](/docs/api-reference/documents/create) is a JSON object. Template strings read from it by dotted path: ```json title="data" { "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 } } ``` - `{{customer.name}}` prints `Northwind Ltd.` - `{{invoice.due_date | date}}` prints `Nov 22, 2026` - A table that repeats over `line_items` with the row alias `item` prints one row per item, and its cells read the row: `{{item.description}}`, `{{item.qty}}`, `{{item.amount | money}}` Paths are dot-separated names made of letters, digits and underscores, and a name can't start with a digit. Template strings can't index into a list (`line_items.0.qty` isn't a valid binding); use a table to print list items. The full syntax is on [Template strings](/docs/concepts/template-strings). ## Declaring variables [#declaring-variables] In the editor, open the **Data** tab in the left panel and click **Add** under **Variables**. Each variable has: - **Path**: `customer.address` for a field of an object, `line_items` for a list, `line_items[].qty` for a field of every item in that list. - **Type**: one of the types below. - **Required**: whether every request must include it. - **Description**: copied into the JSON Schema, so it documents the field for whoever calls the API. Parents are implied: declaring `customer.name` makes `customer` an object, and declaring `line_items[].qty` makes `line_items` a list of objects. You can also declare them explicitly, for example to make the list itself required. Every binding in the template must point to a declared variable. A binding to an undeclared one is a validation error that blocks publishing. Changing a variable's path in the editor also rewrites the bindings that use it. ### Types [#types] | Type | Use it for | JSON Schema | Notes | | --- | --- | --- | --- | | `string` | Text | `{ "type": "string" }` | | | `number` | Quantities, rates | `{ "type": "number" }` | | | `integer` | Counts | `{ "type": "integer" }` | `3.5` is rejected. | | `money` | Amounts | `{ "type": "number" }` | Send a plain number, such as `4800` or `556.8`. | | `date` | Dates | `{ "type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}" }` | Must start with `YYYY-MM-DD`. A time after it is allowed and ignored by the `date` filter. | | `boolean` | Flags, often for visibility conditions | `{ "type": "boolean" }` | | | `image` | Image URLs | `{ "type": "string", "format": "uri" }` | Only public https URLs are fetched. See [Images](#images-barcodes-and-qr-codes). | | `array` | Repeating rows | `{ "type": "array", "items": … }` | Item fields come from the `[]` paths. | | `object` | Groups of fields | `{ "type": "object", "properties": … }` | | The type decides what the schema accepts, not how the value prints. `{{totals.amount}}` prints `7516.8`; `{{totals.amount | money}}` prints `$7,516.80`. Formatting is done with [filters](/docs/concepts/template-strings#filters). ### Required and optional fields [#required-and-optional-fields] - A required field must be present with the right type. An empty string counts as present. - A required field makes its parents required. If `customer.address` is required and the payload has no `customer`, the error names `customer`; if `customer` is there without `address`, it names `customer.address`. - A required list must be present but may be empty (`[]`). Required item fields must be present in every item. - To leave out an optional field, omit the key. `null` isn't accepted for a typed field: `"tax": null` fails with `totals.tax must be number`. ### Lists [#lists] A list variable feeds a table or a chart. Declare the list and the fields of its items: ```text line_items array required line_items[].description string required line_items[].qty number required line_items[].rate money required line_items[].amount money required ``` A list of plain values, such as `["urgent", "fragile"]`, is a list variable without item fields. In a table over it, the row alias is the value itself: with `each` set to `tags` and the alias `tag`, a cell reads `{{tag}}`. ### Images, barcodes and QR codes [#images-barcodes-and-qr-codes] An image block shows either a fixed URL or the URL in an `image` variable. Druckling fetches it while rendering, with these limits: - only public `https://` URLs (no IP addresses or local host names), with no redirects, - PNG, JPEG, GIF, SVG or WebP, up to 5 MB, answering within 4 seconds, - up to 20 different images per document. An image that can't be fetched doesn't fail the render: the block prints its placeholder box instead. The schema accepts any URI (`format: "uri"`), so an `http://` or `data:` URL passes validation but prints the placeholder. A QR / Barcode block's value is a template string, so it binds any string or number variable, for example `{{payment.url}}` or `https://verify.example.com/{{certificate.id}}`. If the value is empty, or the symbology can't encode it (letters in an EAN-13), the code is left out. ## The derived JSON Schema [#the-derived-json-schema] Druckling derives a [JSON Schema](https://json-schema.org/) (draft-07) from the variable list. This is the complete schema of the `invoice-standard` starter, as [`GET /v1/templates/invoice-standard`](/docs/api-reference/templates/get) returns it in `json_schema`: ```json title="json_schema" { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "invoice": { "type": "object", "properties": { "number": { "type": "string", "description": "Invoice number shown in the header" }, "due_date": { "type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}" } }, "required": ["number", "due_date"] }, "customer": { "type": "object", "properties": { "name": { "type": "string" }, "address": { "type": "string" } }, "required": ["name", "address"] }, "line_items": { "type": "array", "items": { "type": "object", "properties": { "description": { "type": "string" }, "qty": { "type": "number" }, "rate": { "type": "number" }, "amount": { "type": "number" } }, "required": ["description", "qty", "rate", "amount"] } }, "totals": { "type": "object", "properties": { "subtotal": { "type": "number" }, "tax": { "type": "number" }, "amount": { "type": "number" } }, "required": ["subtotal", "amount"] }, "payment": { "type": "object", "properties": { "url": { "type": "string" } } } }, "required": ["invoice", "customer", "line_items", "totals"] } ``` A few things follow from it: - **Extra fields are allowed.** The schema doesn't set `additionalProperties: false`, so keys the template doesn't declare pass validation and are ignored by the layout. - **No type coercion.** `"qty": "12"` fails with `line_items.0.qty must be number`. Send numbers as JSON numbers and booleans as `true` or `false`. - **Dates are checked for shape only.** `"22.11.2026"` fails, but `"2026-02-31"` passes; see the warning under [the `date` filter](/docs/concepts/template-strings#date). - **The schema follows the published version.** It changes only when you publish, and the template page's **Schema** tab shows the same schema. In a template with e-invoicing on, `invoice` is the canonical EN 16931 invoice: its schema replaces whatever the template declares under `invoice`, and the schema carries an extra `x-druckling-einvoice` keyword. Druckling also checks the EN 16931 business rules on every render. See [E-invoicing](/docs/guides/e-invoicing). ## Sample data [#sample-data] Every template stores an example payload. The editor preview, **Test PDF**, the preview on the template page and the code samples on its **API** tab use it, and the API returns it as `sample_data`. To change it, open the editor's **Data** tab and edit the JSON under **Sample data**. The panel tells you whether it matches the template's schema; click **Apply** to save it to the draft. **Generate** replaces it with placeholder values derived from the variables, such as names, amounts and dates. Publishing requires the sample data to match the schema and to render, so a published template always comes with a payload that works. `sample_data` from the API comes from the latest published version (or the draft, before the first publish). Sample data is stored with the template and anyone with a **Full access** API key for the workspace can read it. Use realistic but made-up values. ## Validation on every render [#validation-on-every-render] Druckling validates `data` against the schema of the version it renders, before anything is rendered. The same check runs for each item of a [batch](/docs/guides/batches), where one invalid item stops the whole batch. An invalid payload fails with 422. `data.code` is `schema_validation_failed`, `data.field` is the first field to fix, and `data.errors` lists every problem, with fields that are missing first: ```json title="422 Unprocessable Content" { "defined": false, "code": "UNPROCESSABLE_CONTENT", "status": 422, "message": "Required field customer.address was missing from the request payload", "data": { "code": "schema_validation_failed", "field": "customer.address", "documentId": "pdf_8Qw2kLm3nP0aB1cD", "errors": [ { "field": "customer.address", "message": "missing required field customer.address" }, { "field": "invoice.due_date", "message": "invoice.due_date must be a date like 2026-11-22" }, { "field": "line_items.0.qty", "message": "line_items.0.qty must be number" } ] } } ``` `field` is a dotted path with zero-based list indexes: `line_items.0.qty` is `qty` in the first item. The rejected request is still recorded as a `failed` document (`documentId`), so it shows up under **Documents** with its request body, but it doesn't count toward your plan. The SDKs raise a `ValidationError` (`ValidationException` in PHP) that carries the same `field` and `errors`. For the full error format, see [Errors](/docs/concepts/errors#validation-errors). ### Size limits [#size-limits] These limits apply to the payload when it renders, after schema validation: | Limit | Value | Error | | --- | --- | --- | | Payload size | 1,000,000 bytes of JSON | `payload_too_large` (413) | | Items in one list | 10,000 | `payload_too_large` (413) | | Nesting depth | 32 levels | `validation_failed` (422) | For an asynchronous render the request itself succeeds, and the document then fails with that error code. Page limits depend on your plan; see [Plans and limits](/docs/concepts/plans-and-limits#payload-and-render-limits). ## Validate before you call the API [#validate-before-you-call-the-api] You can check payloads in your own code with the template's schema, for example in a form or before queueing work. Fetch the schema once and cache it: it only changes when you publish, and `latest_version` tells you when that happened. Fetching it needs a **Full access** key. ```ts tab="TypeScript" import Ajv from "ajv"; import addFormats from "ajv-formats"; import Druckling from "@druckling/sdk"; const druckling = new Druckling(); const template = await druckling.templates.get("invoice-standard"); // strict: false lets Ajv accept Druckling's x-druckling-einvoice keyword on e-invoice templates. const ajv = new Ajv({ allErrors: true, strict: false }); addFormats(ajv); const validate = ajv.compile(template.json_schema); export function problems(data: unknown): { field: string; message: string }[] { if (validate(data)) return []; return (validate.errors ?? []).map((error) => { const base = error.instancePath.slice(1).replaceAll("/", "."); const field = error.keyword === "required" ? [base, error.params.missingProperty].filter(Boolean).join(".") : base; return { field, message: error.message ?? "is invalid" }; }); } console.log(problems({ invoice: { number: "INV-2042", due_date: "2026-12-01" } })); // [ { field: "customer", ... }, { field: "line_items", ... }, { field: "totals", ... } ] ``` ```python tab="Python" from jsonschema import Draft7Validator from druckling import Druckling client = Druckling() template = client.templates.get("invoice-standard") validator = Draft7Validator(template.json_schema) def problems(data): found = [] for error in validator.iter_errors(data): field = ".".join(str(part) for part in error.absolute_path) if error.validator == "required": missing = error.message.split("'")[1] field = f"{field}.{missing}" if field else missing found.append({"field": field, "message": error.message}) return found print(problems({"invoice": {"number": "INV-2042", "due_date": "2026-12-01"}})) ``` Both produce the same dotted `field` paths as the API. The TypeScript example needs `npm install ajv ajv-formats`, the Python one `pip install jsonschema` (which doesn't check `format: "uri"` unless you pass a format checker). Client-side validation is a convenience, not a replacement for the server's check: Druckling always validates again, and the e-invoice business rules only run on the server. If you pin a `version`, validate against the schema you fetched while that version was the latest, since the API returns the latest version's schema. Bind and format the values you declared. Every error code and how to handle it. # Accessible PDFs (/docs/guides/accessible-pdfs) > Render tagged PDF/UA-1 documents and PDF/A archives, and fix what the accessibility checks report before you publish. Every PDF Druckling renders is tagged: it carries a structure tree that screen readers and other assistive technology can follow. On top of that, a template can claim a PDF standard. PDF/UA-1 makes the document formally accessible, PDF/A makes it fit for long-term archiving, and PDF/A-3a combines archiving with accessibility. This guide explains the standards, what Druckling takes care of, what you have to provide, and how to check the result. ## Choose a PDF standard [#choose-a-pdf-standard] The PDF standard is a template setting. In the editor, select the **Document** tab in the right-hand panel and pick a **PDF standard** under **Output**. It applies to every PDF rendered from the published version; there's no API parameter for it, and a pinned version keeps the standard it was published with. | Setting | What it means | Editor checks | | --- | --- | --- | | **Standard PDF** | A tagged PDF without a conformance claim. The default | Nothing extra | | **PDF/A-2b (archival)** | PDF/A-2, level b, for long-term archiving. No embedded files | Nothing extra | | **PDF/A-3b (archival + attachments)** | PDF/A-3, level b. Allows embedded files such as e-invoice XML | Nothing extra | | **PDF/A-3a (archival + attachments, accessible)** | PDF/A-3, level a: archiving plus accessibility requirements | Alt text on images | | **PDF/UA-1 (accessible)** | PDF/UA-1 (ISO 14289-1), the standard for accessible PDF | Document title, alt text on images, heading order | A PDF claims one standard, so PDF/UA-1 can't be combined with a PDF/A level. If you need an accessible document that is also an archive, or an accessible [Factur-X or ZUGFeRD e-invoice](/docs/guides/e-invoicing), use PDF/A-3a. Factur-X templates only offer PDF/A-3b and PDF/A-3a, because the invoice XML has to be embedded in a PDF/A-3. The European Accessibility Act has applied since 28 June 2025 to many products and services sold to consumers in the EU. If documents such as tickets, contracts or statements are part of a service it covers, PDF/UA-1 is the established way to make them accessible. ## What Druckling does for you [#what-druckling-does-for-you] These apply to every render, whatever standard you choose, unless noted: - **Tagged structure.** Text blocks, headings, tables and images are tagged in the PDF's structure tree. The reading order is the order of the blocks in the template, top to bottom, and inside a columns block one column after the other. - **Headings.** Heading blocks become tagged headings of their level (1 to 3), which also gives PDF viewers a document outline. - **Table headers.** A table's header row is tagged as table headers, so each cell can be read with its column name. With **Repeat header row** on (the default), the header row repeats on every page. - **Headers and footers.** Blocks in the page header and footer are marked as artifacts, so screen readers don't read the running header and page numbers on every page. - **Decorative images.** Images marked **Decorative** are artifacts too, and need no alt text. - **Codes.** QR codes and barcodes get alt text automatically: the kind of code followed by its value, for example `QR code: https://verify.example.com/CERT-8812`. When the value is printed below the code, or spans several lines (like a GiroCode payment QR), the alt text is just the kind, such as `QR code` or `EAN-13 barcode`. - **Title.** The **Title** under **Document** › **Metadata** is written to the PDF's metadata. In PDF/UA-1 documents, PDF viewers show it in the title bar instead of the file name. A template without a title gets `Document`. - **Language.** The PDF declares the language it was rendered in, so screen readers pronounce the text correctly. It's the template's default language, or the `language` of the render; see [Multi-language templates](/docs/guides/languages). ## What you provide [#what-you-provide] The standard can only require what the template supplies. For PDF/UA-1: - **A document title.** Set **Document** › **Metadata** › **Title**, for example `Invoice`. In a multi-language template, translate it like any other text. - **Alt text for images.** Select the image block and fill in **Alt text** with what the image conveys, for example `Logo of Acme Studio`. If the image is only decoration, switch on **Decorative** instead. Placeholders without an image source don't need either. Alt text is plain text: bindings like `{{customer.name}}` aren't filled in. - **Real headings in order.** Use heading blocks for section titles rather than bold text. Start with a level 1 heading and don't skip levels (1, 2, 3, not 1, 3). - **Headings that are never empty.** A heading that is only a binding, such as `{{invoice.number}}`, is empty when the value is missing. Make the variable required, or add a fallback with the `default` filter, for example `{{invoice.number | default:Invoice}}`. A required variable can still be sent as an empty string, which the `default` filter also covers. - **A description for charts.** Charts have no alt text setting. Their title and labels are text, but the bars and lines aren't described, so state what the chart shows in a text block next to it. PDF/A-3a only requires the alt text (or the **Decorative** switch) on images. ## Checks in the editor [#checks-in-the-editor] While you edit a template with PDF/UA-1 or PDF/A-3a, the editor checks it and lists the problems in the status menu above the canvas, marking the blocks they belong to. Only body blocks are checked; header and footer blocks are artifacts. | Message | Standard | Fix | | --- | --- | --- | | PDF/UA needs a document title (Document settings → Title) | PDF/UA-1 | Fill in **Document** › **Metadata** › **Title** | | PDF/UA: add alt text to this image, or mark it decorative | PDF/UA-1 | Fill in **Alt text** or switch on **Decorative** | | PDF/A-3a: add alt text to this image, or mark it decorative | PDF/A-3a | Same | | PDF/UA: the first heading must be level 1, not 2 | PDF/UA-1 | Change the first heading to level 1 | | PDF/UA: heading levels can't skip from 1 to 3 | PDF/UA-1 | Use level 2, or add a level 2 heading in between | | PDF/UA: headings can't be empty | PDF/UA-1 | Give the heading text | These are errors: the template can't be published until they're fixed. One more check is a warning, because it depends on the data: ```text PDF/UA rejects empty headings: make the variable required or add a | default ``` In a multi-language template, the checks run for every language, since a translation can leave a heading or an alt text empty. Problems in another language are prefixed with its name, for example `German: PDF/UA: add alt text to this image, or mark it decorative`. When you publish, Druckling also exports the template once with its sample data in the chosen standard. If the export fails, publishing fails with the reason, and nothing changes for your API calls. ### When data breaks a rule [#when-data-breaks-a-rule] The checks look at the template; the data arrives later. If a render produces something the standard forbids, for example a heading whose only binding is empty in this payload, the render fails with `render_failed`. A synchronous request answers 422: ```json { "defined": false, "code": "UNPROCESSABLE_CONTENT", "status": 422, "message": "PDF/UA-1 error: heading title could not be determined", "data": { "code": "render_failed", "field": null, "diagnostics": [ { "severity": "error", "message": "PDF/UA-1 error: heading title could not be determined", "file": "other" } ] } } ``` The document is recorded as `failed` with this error, which is also what an async render ends with. Fix the data, or make the template robust with required variables and `default` filters. ## PNG output [#png-output] [PNG output](/docs/guides/png-output) has no PDF standard: an image can't be tagged or claim conformance. You can still render a page of a PDF/UA-1 template as a PNG; the document's timeline in the dashboard notes that the standard applies to PDF output only. ## Verify the output [#verify-the-output] Druckling enforces what the export requires, but no tool can judge whether alt text is meaningful or the reading order makes sense. Before relying on a template: 1. Render a few documents with a [test key](/docs/concepts/test-mode), using realistic data, including long values and missing optional fields. 2. Check the files with a validator such as veraPDF, which tests PDF/A and PDF/UA conformance, or an accessibility checker such as PAC. 3. Read a sample with a screen reader, such as NVDA on Windows or VoiceOver on macOS, and listen for the reading order, headings and image descriptions. Render one template in several languages, with the right PDF language. Factur-X and ZUGFeRD invoices as PDF/A-3b or PDF/A-3a. # Batches (/docs/guides/batches) > Render one template for up to 1,000 payloads in a single request and download every file as one ZIP. A batch renders one published template for many payloads: a month of invoices, certificates for a whole course, tickets for an event. You send up to 1,000 items in one request. Druckling checks all of them, renders each one as a regular document, and zips the results when the last one finishes. Use a batch when you have the data for many documents at once and want them as one download. To render documents one at a time as they're needed, call [`POST /v1/documents`](/docs/api-reference/documents/create) instead. ## How a batch works [#how-a-batch-works] 1. **Validation.** Every item's `data` is checked against the template's JSON Schema. If any item is invalid, the whole batch is rejected and nothing is stored or counted. 2. **Queued.** Each item becomes an [asynchronous document](/docs/concepts/documents) whose `batch` is set to its batch ID and position. All items render the same template version, even if you publish a new one while the batch runs. 3. **Running.** The documents render in the background. 4. **Finished.** Once no item is pending, Druckling builds a ZIP of every rendered file and sends the `batch.completed` [webhook](#webhooks). A batch's `status` moves through these values: | Status | Meaning | | --- | --- | | `queued` | Accepted; the item renders haven't been queued yet. | | `running` | Items are rendering. | | `completed` | No item is pending and at least one rendered. `zip_url` is set. Some items may still have failed. | | `failed` | No item rendered, or Druckling couldn't queue the renders or build the ZIP. `error` says which. | | `canceled` | You [canceled](#cancel-a-batch) the batch. There's no ZIP. | `counts` tracks the items: `total`, `pending` (queued or rendering), `rendered`, `failed` and `canceled`. Rendered documents whose files have since expired still count as `rendered`. ## Start a batch [#start-a-batch] Send the template slug and an `items` array to [`POST /v1/batches`](/docs/api-reference/batches/create). Each item has a `data` payload, plus an optional `filename` and `language`. This file renders two invoices from the `invoice-standard` starter template: ```json title="batch.json" { "template": "invoice-standard", "filename_pattern": "invoice-{{invoice.number}}.pdf", "items": [ { "data": { "invoice": { "number": "INV-2041", "due_date": "2026-11-22" }, "customer": { "name": "Northwind Ltd.", "address": "12 Pier St, Leeds" }, "line_items": [{ "description": "Design system audit", "qty": 12, "rate": 180, "amount": 2160 }], "totals": { "subtotal": 2160, "tax": 172.8, "amount": 2332.8 } } }, { "data": { "invoice": { "number": "INV-2042", "due_date": "2026-11-29" }, "customer": { "name": "Fabrikam Inc.", "address": "4 Harbour Rd, Bristol" }, "line_items": [{ "description": "Workshop facilitation", "qty": 2, "rate": 640, "amount": 1280 }], "totals": { "subtotal": 1280, "tax": 102.4, "amount": 1382.4 } } } ] } ``` The [TypeScript, Python and PHP SDKs](/docs/sdks) don't wrap the batch endpoints yet. Call them over plain HTTP, as below. ```bash tab="cURL" curl https://druckling-nine.vercel.app/v1/batches \ -H "Authorization: Bearer $DRUCKLING_API_KEY" \ -H "Content-Type: application/json" \ -d @batch.json ``` ```ts tab="TypeScript" import { readFile } from "node:fs/promises"; const response = await fetch("https://druckling-nine.vercel.app/v1/batches", { method: "POST", headers: { Authorization: `Bearer ${process.env.DRUCKLING_API_KEY}`, "Content-Type": "application/json", }, body: await readFile("batch.json", "utf8"), }); const batch = await response.json(); if (!response.ok) throw new Error(`${response.status}: ${batch.message}`); console.log(batch.id, batch.status); ``` ```python tab="Python" import json import os import httpx with open("batch.json") as f: body = json.load(f) response = httpx.post( "https://druckling-nine.vercel.app/v1/batches", headers={"Authorization": f"Bearer {os.environ['DRUCKLING_API_KEY']}"}, json=body, timeout=60, ) batch = response.json() if response.status_code != 202: raise RuntimeError(f"{response.status_code}: {batch['message']}") print(batch["id"], batch["status"]) ``` ```php tab="PHP" true, CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('DRUCKLING_API_KEY'), 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => file_get_contents('batch.json'), CURLOPT_RETURNTRANSFER => true, ]); $batch = json_decode(curl_exec($ch), true); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); if ($status !== 202) { throw new RuntimeException("$status: " . ($batch['message'] ?? 'request failed')); } echo $batch['id'], ' ', $batch['status'], PHP_EOL; ``` The answer is `202 Accepted` with the new batch: ```json { "id": "bat_3Hk9QmZ1xT7pLw2V", "object": "batch", "status": "queued", "template": "invoice-standard", "version": 1, "filename_pattern": "invoice-{{invoice.number}}.pdf", "counts": { "total": 2, "pending": 2, "rendered": 0, "failed": 0, "canceled": 0 }, "zip_url": null, "zip_size_bytes": null, "zip_expires_at": null, "error": null, "test_mode": true, "created_at": "2026-10-27T09:38:02.114Z", "finished_at": null } ``` The template needs a published version; otherwise the answer is `404`. `version` defaults to `latest`, which is resolved once, when the batch is created. Pass a version number to pin an older one. Any API key can start a batch, including a **Render only** key. ### Languages [#languages] For a [multi-language template](/docs/guides/languages), set `language` on the batch to render every item in that language, and `language` on an item to override it for that item. Without either, items render in the template's default language. A language the template doesn't have rejects the whole batch with `422 validation_failed` on `language` or `items.{n}.language`. ## File names [#file-names] Each item's file name comes from the first of these that is set: 1. The item's own `filename`. 2. `filename_pattern`, rendered with the item's `data`. 3. The default, `{template}-{n}`: the template slug and the item's position, starting at 1. The default number is zero-padded to the width of the item count, so the files sort correctly: `invoice-standard-1.pdf` to `invoice-standard-9.pdf` for 9 items, `invoice-standard-001.pdf` to `invoice-standard-250.pdf` for 250. `filename_pattern` uses `{{path}}` bindings into the item's data, such as `invoice-{{invoice.number}}.pdf`. Three filters work: `upper`, `lower`, and `default:"…"` for a fallback when the value is empty. Other filters are ignored and insert the raw value. Bindings only insert strings, numbers and booleans; a missing field, an object or an array inserts nothing. A pattern with an unclosed `{{` is rejected with `422` on `filename_pattern`. Druckling then cleans up each name: - Slashes and control characters inside a value become `-`. Any left in the pattern itself or in an item's `filename` are removed, so the ZIP never has folders. - Spaces, dots, dashes and underscores at either end are trimmed, so a binding that resolved to nothing doesn't leave `invoice-.pdf`. If nothing is left, the default name is used. - The extension always matches the output: `.pdf`, or `.xml` for [XRechnung and Peppol templates](/docs/guides/e-invoicing). A trailing `.pdf`, `.png` or `.xml` is replaced. Any other extension stays part of the name, so `report.docx` becomes `report.docx.pdf`. - Names are made unique within the batch, ignoring case: a second `invoice-INV-2041.pdf` becomes `invoice-INV-2041-2.pdf`. With `"filename_pattern": "invoice-{{invoice.number}}.pdf"`: | Item | File name | | --- | --- | | `invoice.number` is `INV-2041` | `invoice-INV-2041.pdf` | | A later item whose `invoice.number` is `inv-2041` | `invoice-inv-2041-2.pdf` | | `invoice.number` is `INV/2042` | `invoice-INV-2042.pdf` | | No `invoice.number` | `invoice.pdf` | | The item sets `"filename": "custom.pdf"` | `custom.pdf` | Names are at most 200 characters. The same name is each document's `filename`. ## Validation comes first [#validation-comes-first] Druckling validates every item before it stores anything. If one item is invalid, the batch is rejected as a whole, so a run never ships with silent gaps. The answer is `422` and lists the first problem of each invalid item: ```json { "defined": false, "code": "UNPROCESSABLE_CONTENT", "status": 422, "message": "Item 1: Required field customer.address was missing from the request payload (2 of 3 items are invalid)", "data": { "code": "schema_validation_failed", "field": "items.1.data.customer.address", "invalidItems": 2, "errors": [ { "index": 1, "field": "customer.address", "message": "Required field customer.address was missing from the request payload" }, { "index": 2, "field": "invoice.due_date", "message": "Invoice.due_date must be a date like 2026-11-22" } ] } } ``` - `data.errors` has one entry per invalid item, in item order, for the first 20 invalid items. `index` is the item's position in `items`, starting at 0, and `field` is the path inside its `data`. - `data.invalidItems` counts every invalid item, including those past the first 20. - `data.field` points at the first problem as a full path into the request. - `data.code` is `schema_validation_failed` for schema errors and `validation_failed` for broken business rules, such as [e-invoice](/docs/guides/e-invoicing) rules. Nothing was stored or counted, so fix the items and send the whole batch again. To catch problems earlier, fetch the template's schema from [`GET /v1/templates/{slug}`](/docs/api-reference/templates/get) and validate payloads as you build them. See [Variables and JSON Schema](/docs/concepts/variables) and [Errors](/docs/concepts/errors). ## Limits [#limits] | Limit | Value | When exceeded | | --- | --- | --- | | Items per batch | 1 to 1,000 | `400` request validation error | | Size of `items` as JSON | 4 MB | `413 payload_too_large` | | `filename_pattern` and each item's `filename` | 200 characters | `400` request validation error | | Documents left on your plan, in live mode | The whole batch must fit | `429 quota_exceeded` | A live batch must fit into the documents your plan has left today and this month, after any renders already queued in the workspace. If it doesn't, it's rejected and nothing is stored. Each item that renders counts as one document; failed and canceled items don't count. Test batches are never limited. See [Plans and limits](/docs/concepts/plans-and-limits). Split larger jobs into several batches. They run independently. ## Track progress [#track-progress] Poll [`GET /v1/batches/{id}`](/docs/api-reference/batches/get) for the status and live counts, or subscribe to the [`batch.completed` webhook](#webhooks) instead. ```bash curl https://druckling-nine.vercel.app/v1/batches/bat_3Hk9QmZ1xT7pLw2V \ -H "Authorization: Bearer $DRUCKLING_API_KEY" ``` A loop that waits until the batch has finished: ```ts async function waitForBatch(id: string) { for (;;) { const response = await fetch(`https://druckling-nine.vercel.app/v1/batches/${id}`, { headers: { Authorization: `Bearer ${process.env.DRUCKLING_API_KEY}` }, }); const batch = await response.json(); if (batch.status !== "queued" && batch.status !== "running") return batch; await new Promise((resolve) => setTimeout(resolve, 5_000)); } } ``` [`GET /v1/batches`](/docs/api-reference/batches/list) lists your batches, newest first, optionally filtered by `status`. ### Find the items that failed [#find-the-items-that-failed] [`GET /v1/batches/{id}/documents`](/docs/api-reference/batches/documents) lists the batch's documents in item order. Filter by `outcome` (`pending`, `rendered`, `failed` or `canceled`) to see only the items that need attention: ```bash curl "https://druckling-nine.vercel.app/v1/batches/bat_3Hk9QmZ1xT7pLw2V/documents?outcome=failed" \ -H "Authorization: Bearer $DRUCKLING_API_KEY" ``` Each document has `batch.index`, its position in your `items`, and an `error` with a `code`, a `message` and, where it applies, a `field`. Page through long lists with `limit` (up to 100) and `cursor`, passing the `next_cursor` of the previous page. Documents in list responses have no `url`. To download a single item, fetch it with [`GET /v1/documents/{id}`](/docs/api-reference/documents/get). Batch items also appear in [`GET /v1/documents`](/docs/api-reference/documents/list) like any other document. To retry failed items, map each `batch.index` back to your own records, fix the data, and send those items as a new batch. ## Download the ZIP [#download-the-zip] When no item is pending, Druckling builds the ZIP and the batch becomes `completed`, with a signed download link in `zip_url`: ```json { "id": "bat_3Hk9QmZ1xT7pLw2V", "object": "batch", "status": "completed", "template": "invoice-standard", "version": 1, "filename_pattern": "invoice-{{invoice.number}}.pdf", "counts": { "total": 2, "pending": 0, "rendered": 2, "failed": 0, "canceled": 0 }, "zip_url": "https://files.example.com/bat_3Hk9QmZ1xT7pLw2V.zip?signature=…", "zip_size_bytes": 72311, "zip_expires_at": "2026-11-26T09:38:41.902Z", "error": null, "test_mode": true, "created_at": "2026-10-27T09:38:02.114Z", "finished_at": "2026-10-27T09:38:41.902Z" } ``` - The ZIP holds every rendered file, flat and in item order, under the [file names](#file-names) above. Failed and canceled items aren't in it. Files are stored without further compression, since PDFs are compressed already. - `zip_url` works for up to 7 days, and never past `zip_expires_at`. Every `GET` returns a fresh link, so fetch the batch again rather than storing the URL. - The ZIP is kept for 30 days after the batch completes (`zip_expires_at`), then deleted; from then on `zip_url` is `null`. Each item's file follows the usual [document retention](/docs/concepts/documents), and batch records are kept for a year. A batch where nothing rendered ends `failed` without a ZIP, with an error such as `{ "code": "render_failed", "message": "None of the 2 documents rendered" }`. If the ZIP itself can't be built, the batch fails with `zip_failed`, and the rendered documents stay available one by one. ## Cancel a batch [#cancel-a-batch] [`POST /v1/batches/{id}/cancel`](/docs/api-reference/batches/cancel) stops a `queued` or `running` batch: ```bash curl -X POST https://druckling-nine.vercel.app/v1/batches/bat_3Hk9QmZ1xT7pLw2V/cancel \ -H "Authorization: Bearer $DRUCKLING_API_KEY" ``` - Items that haven't started rendering become `failed` documents with error code `canceled`, counted in `counts.canceled`. - Renders that are already running finish, and their documents stay available. `counts` keeps changing until they do. - A canceled batch never gets a ZIP. - Once a batch has finished, canceling answers `409 invalid_state`. ## Webhooks [#webhooks] Subscribe a [webhook endpoint](/docs/guides/webhooks) to `batch.completed` to hear when a batch finishes instead of polling. It's sent once per batch, when the batch becomes `completed`, `failed` or `canceled`. `data` is the batch, including `zip_url`: ```json { "id": "evt_5Rn2XqK8wT1mZp4L", "object": "event", "type": "batch.completed", "created_at": "2026-10-27T09:38:41.902Z", "test_mode": true, "data": { "id": "bat_3Hk9QmZ1xT7pLw2V", "object": "batch", "status": "completed", "template": "invoice-standard", "version": 1, "filename_pattern": "invoice-{{invoice.number}}.pdf", "counts": { "total": 2, "pending": 0, "rendered": 2, "failed": 0, "canceled": 0 }, "zip_url": "https://files.example.com/bat_3Hk9QmZ1xT7pLw2V.zip?signature=…", "zip_size_bytes": 72311, "zip_expires_at": "2026-11-26T09:38:41.902Z", "error": null, "test_mode": true, "created_at": "2026-10-27T09:38:02.114Z", "finished_at": "2026-10-27T09:38:41.902Z" } } ``` Batch items are ordinary documents, so they also send `document.rendered` and `document.failed` events, with `data.batch` set, and later `document.expired`. A 1,000-item batch can send over a thousand document events. If you only care about the run as a whole, subscribe that endpoint to `batch.completed` alone. Canceled items, and items that never started rendering, don't send `document.failed`; `batch.completed` covers them. ## Run a batch from the dashboard [#run-a-batch-from-the-dashboard] You can start the same batch from a spreadsheet, without code, under **Automate › Batches**. Batches started through the API show up there too. ### Choose the template [#choose-the-template] Click **New batch** and pick a published template. Dashboard batches render its latest published version. If the template has several languages, pick the one to render every file in. ### Upload your data [#upload-your-data] Drop a CSV or JSON file with up to 1,000 rows. The file can be up to 10 MB, and the data built from it up to 4 MB. **Sample CSV for this template** downloads a CSV with one column per variable and the template's sample data as its only row, a good starting point. Optionally enter a file name pattern, such as `invoice-{{invoice.number}}.pdf`. ### Map columns [#map-columns] For a CSV, match each column to a template variable, to **File name**, or to **Don't use**. Each variable takes one column. Required variables are marked with `*`, and Druckling warns when one has no column. ### Check and start [#check-and-start] Druckling validates every row against the template's schema and shows how many are ready and which need fixing, by line number. Fix the file and upload it again, or choose to skip the rows that need fixing and render the rest. In live mode, this step also shows how many documents your plan has left. The batch runs in the mode the dashboard is in, test or live. Its details show **Dashboard** where API batches show the key's name. ### CSV format [#csv-format] ```csv title="invoices.csv" invoice.number,invoice.due_date,customer.name,customer.address,line_items,totals.subtotal,totals.tax,totals.amount,File name INV-2041,2026-11-22,Northwind Ltd.,"12 Pier St, Leeds","[{""description"":""Design system audit"",""qty"":12,""rate"":180,""amount"":2160}]",2160,172.8,2332.8,northwind-2041.pdf INV-2042,2026-11-29,Fabrikam Inc.,"4 Harbour Rd, Bristol","[{""description"":""Workshop facilitation"",""qty"":2,""rate"":640,""amount"":1280}]",1280,102.4,1382.4, ``` - **Header row.** The first row names the columns, and the separator is detected from it: comma, semicolon or tab. Quoted cells, doubled quotes (`""`), line breaks inside quotes and a UTF-8 byte order mark are all fine; blank lines are skipped. - **Nested fields.** Headers are dotted variable paths, such as `customer.name`, and build nested objects. Druckling maps a header that matches a path exactly, matches it ignoring case and punctuation (`Customer Name` → `customer.name`), or matches its last segment when that's unambiguous (`address` → `customer.address`). A column named `filename`, `file`, `File name`, `PDF name` or `Dateiname` maps to **File name**. Other columns start as **Don't use**, and you can change any mapping. - **File names.** A **File name** cell sets that row's name. Rows where it's empty, like the second row above, fall back to the pattern or the default name. - **Lists.** An array variable, such as `line_items`, is one column holding JSON, as in the example. - **Types.** Cells are converted to the type the template's schema expects. Numbers accept one decimal separator, `.` or `,`, and spaces between digit groups: `1 234,5` becomes `1234.5`, but `1,234.50` and `1.234,50` stay text and fail validation. `true`, `yes`, `y`, `1` and `false`, `no`, `n`, `0` become booleans, ignoring case. Date variables need dates like `2026-11-22`. A cell that doesn't convert stays text, so validation can point at it. - **Empty cells** are left out of the payload, so an empty required field fails validation. A CSV can't set a language per row. For that, upload JSON. ### JSON format [#json-format] Upload a plain array of payloads, or the same body you'd send to the API, including `items[].filename`, `items[].language`, `filename_pattern` and `language`: ```json title="invoices.json" [ { "invoice": { "number": "INV-2041", "due_date": "2026-11-22" }, "customer": { "name": "Northwind Ltd.", "address": "12 Pier St, Leeds" }, "line_items": [{ "description": "Design system audit", "qty": 12, "rate": 180, "amount": 2160 }], "totals": { "subtotal": 2160, "tax": 172.8, "amount": 2332.8 } } ] ``` ## Test mode [#test-mode] A batch started with an `dr_test_…` key, or from the dashboard in test mode, is a test batch. Its `test_mode` is `true`, it never counts toward your plan, and it only shows up in test mode. Its webhooks go to test endpoints only. See [Test mode](/docs/concepts/test-mode). # E-invoicing (/docs/guides/e-invoicing) > Render EN 16931 e-invoices from one invoice payload, as ZUGFeRD and Factur-X PDFs or as XRechnung and Peppol BIS XML. Druckling produces EN 16931 e-invoices from the same API call that renders any other document. You send the invoice data in `data.invoice`. Druckling computes the line totals, the VAT breakdown and the amount due, checks the business rules, and returns either a PDF/A-3 with the XML embedded or the XML on its own. The template decides which. This guide covers choosing a format, setting up a template, the invoice payload field by field, what Druckling calculates for you, and how rule violations come back. ## Choose a format [#choose-a-format] An e-invoice template has one output format. All three are built from the same `invoice` payload, so you can switch a template between them without changing your integration's data. | Format | What you get | XML syntax | Use it for | | --- | --- | --- | --- | | Factur-X 1.0 / ZUGFeRD 2.x | A PDF/A-3 people can read, with the invoice XML embedded as `factur-x.xml` | UN/CEFACT CII D16B | B2B invoices in Germany (ZUGFeRD) and France (Factur-X), where the buyer accepts a hybrid PDF | | XRechnung 3.0 | The XML on its own | UBL 2.1 (default) or UN/CEFACT CII D16B | German public-sector buyers, who identify themselves with a Leitweg-ID | | Peppol BIS Billing 3.0 | The XML on its own | UBL 2.1 | Exchange over the Peppol network (Belgium, the Netherlands, the Nordics and more) | Each format writes its specification identifier (BT-24) into the XML, and the document resource reports it back: | Format | `einvoice.profile` | `einvoice.customization_id` (BT-24) | Business process (BT-23) | | --- | --- | --- | --- | | Factur-X / ZUGFeRD | `EN 16931` | `urn:cen.eu:en16931:2017` | Not written | | XRechnung | `XRechnung 3.0` | `urn:cen.eu:en16931:2017#compliant#urn:xeinkauf.de:kosit:xrechnung_3.0` | `urn:fdc:peppol.eu:2017:poacc:billing:01:1.0` | | Peppol BIS | `Peppol BIS Billing 3.0` | `urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0` | `urn:fdc:peppol.eu:2017:poacc:billing:01:1.0` | Factur-X and ZUGFeRD invoices are always produced at the EN 16931 profile (called COMFORT in older ZUGFeRD versions). The MINIMUM, BASIC WL, BASIC and EXTENDED profiles aren't available. Druckling generates the invoice file and returns a download link. It doesn't transmit invoices. To send a Peppol BIS invoice over the Peppol network, hand the XML to your Peppol access point; for French e-invoicing platforms or German public-sector portals, upload it the way they require. ## Set up an e-invoice template [#set-up-an-e-invoice-template] ### Start from a starter or an existing template [#start-from-a-starter-or-an-existing-template] The quickest start is a starter: in the dashboard, go to **Templates** › **New template** and pick **Rechnung (ZUGFeRD)** (German, with the §14 UStG details and a GiroCode payment QR) or **Facture (Factur-X)** (French, with the mandatory mentions as invoice notes). Both come with the invoice variables, a layout with a VAT breakdown, PDF/A-3b and a sample invoice that passes the rules. To turn an existing template into an e-invoice, open it with **Open editor**, select the **Document** tab in the right-hand panel and, under **Output**, switch on **E-invoice (EN 16931)**. ### Choose the e-invoice format [#choose-the-e-invoice-format] Under **Output** › **E-invoice format**, choose **Factur-X / ZUGFeRD (PDF)**, **XRechnung (XML)** or **Peppol BIS Billing 3.0 (XML)**. For XRechnung, also pick a **Syntax**: UBL 2.1 or UN/CEFACT CII. Both are valid XRechnung. Turning e-invoicing on, or changing the format, sets up what the format needs: - It declares the canonical `invoice.*` variables, including the amounts Druckling computes. - For Factur-X, it sets **PDF standard** to PDF/A-3b if the template had something else. Factur-X only allows PDF/A-3b or PDF/A-3a, the PDF/A parts that permit embedded files. Choose PDF/A-3a for an accessible invoice (see [Accessible PDFs](/docs/guides/accessible-pdfs)). - If the sample data doesn't pass the new format's rules, it's replaced with a sample invoice that does. XRechnung and Peppol templates render XML only. Their layout is used for the editor preview; the **PDF standard** setting has no effect on them. ### Bind the layout to the invoice [#bind-the-layout-to-the-invoice] Bind your blocks to `invoice.*` paths, for example `{{invoice.number}}`, `{{invoice.seller.name}}`, a table over `invoice.lines` and another over `invoice.vat_breakdown`. Use the computed amounts (`invoice.totals.grand_total`, `line.net_amount`) instead of calculating totals yourself, so the visible PDF shows exactly the numbers in the XML. Show VAT rates with `{{line.vat_rate | number:0-2}}` to print `19` and `5.5` without trailing zeros. Variables outside `invoice` work as in any template, for example a `logo_url` or a marketing message. A variable you declare under `invoice.` that isn't part of the invoice model gets a warning in the editor: it's neither validated nor written to the XML. ### Publish [#publish] Publishing checks the sample invoice against the same rules as an API request, so a template can't go live with a sample that would be rejected. Problems show in the status menu above the canvas while you edit. ## Render an e-invoice [#render-an-e-invoice] Send the invoice in `data.invoice` to [`POST /v1/documents`](/docs/api-reference/documents/create). This request is valid for a Factur-X template created from the **Rechnung (ZUGFeRD)** starter; replace `rechnung` with your template's slug. ```json title="request.json" { "template": "rechnung", "filename": "RE-2026-0042.pdf", "data": { "invoice": { "number": "RE-2026-0042", "type_code": "380", "issue_date": "2026-10-20", "currency": "EUR", "order_reference": "PO-7781", "delivery_date": "2026-10-15", "seller": { "name": "Acme Studio GmbH", "legal_id": "HRB 123456 B", "legal_info": "Amtsgericht Berlin-Charlottenburg HRB 123456 B · Managing director: Ada Weber", "vat_id": "DE123456789", "tax_number": "37/123/45678", "address": { "line1": "Lindenstraße 12", "postcode": "10969", "city": "Berlin", "country": "DE" }, "electronic_address": "billing@acme-studio.example", "contact": { "name": "Ada Weber", "phone": "+49 30 1234567", "email": "billing@acme-studio.example" } }, "buyer": { "name": "Northwind Handels AG", "id": "K-1001", "address": { "line1": "Hafenweg 3", "postcode": "20457", "city": "Hamburg", "country": "DE" }, "electronic_address": "purchasing@northwind.example" }, "lines": [ { "id": "1", "name": "Brand identity, phase 2", "quantity": 1, "unit_code": "C62", "net_price": 4800, "vat_category": "S", "vat_rate": 19 }, { "id": "2", "name": "Design system audit", "quantity": 12, "unit_code": "HUR", "net_price": 180, "vat_category": "S", "vat_rate": 19 }, { "id": "3", "name": "Book: Typography on the web", "quantity": 2, "unit_code": "H87", "net_price": 39.9, "vat_category": "S", "vat_rate": 7 } ], "allowances_charges": [ { "kind": "allowance", "amount": 100, "reason": "Loyalty discount", "reason_code": "95", "vat_category": "S", "vat_rate": 19 } ], "payment": { "terms": "Payable within 30 days without deduction.", "due_date": "2026-11-19", "reference": "RE-2026-0042", "means_code": "58", "iban": "DE02120300000000202051", "bic": "BYLADEM1001", "account_name": "Acme Studio GmbH" } } } } ``` ```bash tab="cURL" curl https://druckling-nine.vercel.app/v1/documents \ -H "Authorization: Bearer $DRUCKLING_API_KEY" \ -H "Content-Type: application/json" \ --data @request.json ``` ```ts tab="TypeScript" import { readFile } from "node:fs/promises"; import Druckling from "@druckling/sdk"; const druckling = new Druckling(); // reads DRUCKLING_API_KEY const { data } = JSON.parse(await readFile("request.json", "utf8")); const document = await druckling.documents.create({ template: "rechnung", filename: "RE-2026-0042.pdf", data }); console.log(document.einvoice?.format, document.url); // factur-x https://… ``` ```python tab="Python" import json from druckling import Druckling client = Druckling() # reads DRUCKLING_API_KEY with open("request.json", encoding="utf-8") as f: data = json.load(f)["data"] document = client.documents.create(template="rechnung", filename="RE-2026-0042.pdf", data=data) print(document.einvoice.format, document.url) # factur-x https://… ``` ```php tab="PHP" documents->create(template: 'rechnung', data: $data, filename: 'RE-2026-0042.pdf'); echo $document->einvoice->format, ' ', $document->url; // factur-x https://… ``` The response is a [document](/docs/concepts/documents) with an `einvoice` object: ```json { "id": "pdf_8Qw2kLm3nP0aB1cD", "object": "document", "status": "rendered", "template": "rechnung", "version": 1, "filename": "RE-2026-0042.pdf", "format": "pdf", "content_type": "application/pdf", "image": null, "pages": 1, "size_bytes": 48211, "url": "https://…", "expires_at": "2026-11-19T09:14:03.000Z", "error": null, "einvoice": { "format": "factur-x", "syntax": "cii", "profile": "EN 16931", "customization_id": "urn:cen.eu:en16931:2017", "attachment": "factur-x.xml" }, "batch": null, "language": "de", "test_mode": true, "created_at": "2026-10-20T09:14:02.000Z" } ``` The PDF is a PDF/A-3 with `factur-x.xml` attached (relationship `Alternative`, MIME type `text/xml`) and the Factur-X XMP metadata that readers look for: document type `INVOICE`, version `1.0`, conformance level `EN 16931`. The payload is validated before anything is rendered or queued. With `async: true` a valid invoice comes back with status `queued`, but an invalid one still fails right away with a 422, just like a synchronous request. ## The invoice payload [#the-invoice-payload] `data.invoice` is an EN 16931 invoice in snake_case. Amounts are decimal numbers in the invoice currency, dates are `YYYY-MM-DD` strings and codes are strings, even when they look like numbers (`"380"`, `"58"`). The JSON Schema returned by [`GET /v1/templates/{slug}`](/docs/api-reference/templates/get) describes the same object, with each field's business term (BT) in its description. Fields you send that aren't part of the model are accepted, but they aren't validated and never reach the XML. The tables list required fields as EN 16931 requires them. XRechnung and Peppol make more fields mandatory; those appear under [Business rules](#business-rules) and in the required column as "XRechnung" or "Peppol". ### Invoice [#invoice] | Field | Type | Required | BT | Description | | --- | --- | --- | --- | --- | | `number` | string | Yes | BT-1 | Invoice number | | `type_code` | string | No | BT-3 | `380` invoice (default), `381` credit note, `384` corrected invoice, `389` self-billed invoice, `326` partial invoice, `875` partial construction invoice, `876` partial final construction invoice, `877` final construction invoice | | `issue_date` | date | Yes | BT-2 | Issue date | | `currency` | string | Yes | BT-5 | ISO 4217 code in capitals, e.g. `EUR` | | `buyer_reference` | string | XRechnung | BT-10 | Buyer reference. For German public buyers, their Leitweg-ID | | `order_reference` | string | No | BT-13 | Purchase order reference | | `preceding_invoice` | string | No | BT-25 | Invoice a credit note or correction refers to | | `preceding_invoice_date` | date | No | BT-26 | Issue date of the preceding invoice | | `delivery_date` | date | No | BT-72 | Date of supply or service | | `billing_period.start` | date | No | BT-73 | Service period start | | `billing_period.end` | date | No | BT-74 | Service period end | | `notes` | array | No | BG-1 | Invoice notes, see [Notes and delivery](#notes-and-delivery) | | `seller` | object | Yes | | See [Seller and buyer](#seller-and-buyer) | | `buyer` | object | Yes | | See [Seller and buyer](#seller-and-buyer) | | `delivery` | object | No | | Deliver-to party, see [Notes and delivery](#notes-and-delivery) | | `lines` | array | Yes | BG-25 | Invoice lines, see [Lines](#lines) | | `allowances_charges` | array | No | BG-20, BG-21 | Document-level allowances and charges, see [Allowances and charges](#allowances-and-charges) | | `vat_exemptions` | array | No | | Exemption reasons per VAT category, see [VAT categories](#vat-categories) | | `payment` | object | No | | Payment terms and instructions, see [Payment](#payment) | | `prepaid_amount` | number | No | BT-113 | Amount already paid, at most 2 decimals | ### Seller and buyer [#seller-and-buyer] `seller` and `buyer` share one shape. Where the business terms differ, the table shows the seller's first. | Field | Type | Required | BT (seller / buyer) | Description | | --- | --- | --- | --- | --- | | `name` | string | Yes | BT-27 / BT-44 | Legal name | | `trading_name` | string | No | BT-28 / BT-45 | Trading name, if different | | `id` | string | No | BT-29 / BT-46 | Seller identifier; for the buyer, your customer number | | `legal_id` | string | No | BT-30 / BT-47 | Legal registration, e.g. `HRB 123456 B` or a SIREN | | `legal_id_scheme` | string | No | | ISO 6523 scheme of `legal_id`, e.g. `0002` for SIREN, `0208` for a Belgian enterprise number | | `legal_info` | string | No | BT-33 (seller only) | Additional legal information, e.g. register court and share capital | | `tax_number` | string | No | BT-32 (seller only) | National tax number (Steuernummer) | | `vat_id` | string | No | BT-31 / BT-48 | VAT identifier with its country prefix, e.g. `DE123456789` | | `address` | object | Yes | | See the address table below | | `electronic_address` | string | XRechnung, Peppol | BT-34 / BT-49 | E-mail address, Leitweg-ID or Peppol participant identifier | | `electronic_address_scheme` | string | Peppol | | EAS code of `electronic_address`. Default `EM` (e-mail), which Peppol doesn't accept. Common codes: `0204` Leitweg-ID, `9930` German VAT number, `0208` Belgian enterprise number, `0088` GLN | | `contact.name` | string | XRechnung (seller) | BT-41 / BT-56 | Contact person or department | | `contact.phone` | string | XRechnung (seller) | BT-42 / BT-57 | Contact phone | | `contact.email` | string | XRechnung (seller) | BT-43 / BT-58 | Contact e-mail | The `address` object: | Field | Type | Required | BT (seller / buyer) | Description | | --- | --- | --- | --- | --- | | `line1` | string | No | BT-35 / BT-50 | Street and number | | `line2` | string | No | BT-36 / BT-51 | Address line 2 | | `line3` | string | No | BT-162 / BT-163 | Address line 3 | | `postcode` | string | XRechnung | BT-38 / BT-53 | Post code | | `city` | string | XRechnung | BT-37 / BT-52 | City | | `region` | string | No | BT-39 / BT-54 | Region or state | | `country` | string | Yes | BT-40 / BT-55 | ISO 3166-1 alpha-2 code in capitals, e.g. `DE` | ### Lines [#lines] Each item of `lines` is one invoice line. | Field | Type | Required | BT | Description | | --- | --- | --- | --- | --- | | `id` | string | No | BT-126 | Line number. Defaults to the line's position (`"1"`, `"2"`, …) | | `name` | string | Yes | BT-153 | Item name | | `description` | string | No | BT-154 | Item description | | `seller_item_id` | string | No | BT-155 | Your item number | | `note` | string | No | BT-127 | Line note | | `quantity` | number | Yes | BT-129 | Invoiced quantity | | `unit_code` | string | Yes | BT-130 | UN/ECE Recommendation 20 unit, 2 or 3 capitals or digits: `C62` one, `H87` piece, `HUR` hour, `DAY` day | | `net_price` | number | Yes | BT-146 | Net unit price. Can't be negative | | `price_base_quantity` | number | No | BT-149 | Quantity the price refers to. Default 1, must be positive | | `vat_category` | string | Yes | BT-151 | VAT category code, see [VAT categories](#vat-categories) | | `vat_rate` | number | No | BT-152 | VAT rate in percent, e.g. `19` or `5.5`. Unset counts as 0 | ### Allowances and charges [#allowances-and-charges] Document-level discounts and surcharges go in `allowances_charges`. Each one belongs to a VAT category and rate, and Druckling subtracts or adds it in that group of the VAT breakdown. | Field | Type | Required | BT (allowance / charge) | Description | | --- | --- | --- | --- | --- | | `kind` | string | Yes | | `allowance` or `charge` | | `amount` | number | Yes | BT-92 / BT-99 | Positive amount, at most 2 decimals | | `reason` | string | One of the two | BT-97 / BT-104 | Reason text | | `reason_code` | string | One of the two | BT-98 / BT-105 | Reason code: UNCL 5189 for allowances (e.g. `95` discount), UNCL 7161 for charges (e.g. `FC` freight) | | `vat_category` | string | Yes | BT-95 / BT-102 | VAT category code | | `vat_rate` | number | No | BT-96 / BT-103 | VAT rate in percent | ### VAT categories [#vat-categories] `vat_category` takes a UNCL 5305 code. Some categories need a reason in `vat_exemptions`, an array with one entry per category: | Field | Type | Required | BT | Description | | --- | --- | --- | --- | --- | | `category` | string | Yes | | The VAT category the reason applies to | | `reason` | string | One of the two | BT-120 | Exemption reason text, printed in the VAT breakdown | | `code` | string | One of the two | BT-121 | Exemption reason code, e.g. `VATEX-EU-AE` | | Code | Meaning | Rate | Also needs | | --- | --- | --- | --- | | `S` | Standard rate | Above 0 | Seller VAT ID or tax number | | `Z` | Zero rated | 0 | Seller VAT ID or tax number. No exemption reason | | `E` | Exempt from VAT | 0 | Seller VAT ID or tax number, exemption reason | | `AE` | Reverse charge | 0 | Seller VAT ID or tax number, buyer VAT ID (or legal ID), exemption reason | | `K` | Intra-community supply | 0 | Seller and buyer VAT IDs, a delivery date or billing period, the deliver-to country, exemption reason | | `G` | Export outside the EU | 0 | Seller VAT ID, exemption reason | | `O` | Not subject to VAT | None, any rate is ignored | No VAT IDs on either party, exemption reason | | `L` | Canary Islands (IGIC) | Above 0 | Seller VAT ID or tax number | | `M` | Ceuta and Melilla (IPSI) | Above 0 | Seller VAT ID or tax number | ### Payment [#payment] | Field | Type | Required | BT | Description | | --- | --- | --- | --- | --- | | `terms` | string | See below | BT-20 | Payment terms | | `due_date` | date | See below | BT-9 | Due date | | `reference` | string | No | BT-83 | Remittance information, e.g. the invoice number | | `means_code` | string | XRechnung | BT-81 | UNCL 4461 payment means: `58` SEPA credit transfer, `59` SEPA direct debit, `30` credit transfer, `49` direct debit, `48` bank card, `10` cash, `57` standing agreement, `ZZZ` mutually defined | | `iban` | string | For `30` and `58` | BT-84 | Payee IBAN | | `bic` | string | No | BT-86 | Payee BIC | | `account_name` | string | No | BT-85 | Payee account name | | `mandate_id` | string | For `59` in XRechnung, `49` and `59` in Peppol | BT-89 | Direct debit mandate reference | | `creditor_id` | string | For `59` in XRechnung | BT-90 | Your SEPA creditor identifier | | `debited_account` | string | For `59` in XRechnung | BT-91 | The buyer's IBAN to debit | When an amount is due, the invoice needs a `due_date` or `terms` (BR-CO-25). ### Notes and delivery [#notes-and-delivery] | Field | Type | Required | BT | Description | | --- | --- | --- | --- | --- | | `notes[].text` | string | Yes | BT-22 | Note text | | `notes[].subject_code` | string | No | BT-21 | UNTDID 4451 subject, e.g. `AAB`, `PMT`, `PMD`, `REG`, `AAI` | | `delivery.name` | string | No | BT-70 | Deliver-to party name | | `delivery.address.line1` | string | No | BT-75 | Deliver-to street | | `delivery.address.postcode` | string | No | BT-78 | Deliver-to post code | | `delivery.address.city` | string | No | BT-77 | Deliver-to city | | `delivery.address.country` | string | No | BT-80 | Deliver-to country code. The deliver-to address is only written to the XML when it's set | ## What Druckling computes [#what-druckling-computes] Don't send totals. Druckling calculates them from the lines, allowances and charges, writes them to the XML and makes them available to the template, so the PDF and the XML always agree. | Computed field | BT | How it's calculated | | --- | --- | --- | | `lines[].net_amount` | BT-131 | `quantity` × `net_price` ÷ `price_base_quantity`, rounded to cents | | `allowances_charges[].signed_amount` | | The amount, negative for allowances (handy in a table) | | `vat_breakdown[]` | BG-23 | One entry per VAT category and rate: `category` (BT-118), `rate` (BT-119), `basis` (BT-116), `tax` (BT-117), `exemption_reason` (BT-120) | | `totals.line_total` | BT-106 | Sum of line net amounts | | `totals.allowance_total` | BT-107 | Sum of allowances | | `totals.charge_total` | BT-108 | Sum of charges | | `totals.tax_basis_total` | BT-109 | Line total − allowances + charges | | `totals.tax_total` | BT-110 | Sum of the breakdown's VAT amounts | | `totals.grand_total` | BT-112 | Total without VAT + total VAT | | `totals.prepaid` | BT-113 | `prepaid_amount`, or 0 | | `totals.due_payable` | BT-115 | Grand total − prepaid | How the arithmetic works: - **VAT is calculated once per group.** Each VAT breakdown entry adds the line net amounts of its category and rate, subtracts its allowances and adds its charges; the VAT is that basis × rate, rounded once. Druckling never rounds VAT per line, as EN 16931 requires. - **Exact decimals.** Amounts are calculated in fixed-point decimals, not floating point, and rounded half away from zero to cents. Three items at `0.335` make `1.01`, not `1.00`. - **Precision of your inputs.** Quantities and prices can have more than two decimals. Allowance and charge amounts and `prepaid_amount` can have at most two (BR-DEC-01, BR-DEC-16). - **Anything you send is overwritten.** If your payload contains `totals`, `vat_breakdown` or `lines[].net_amount`, Druckling replaces them with its own values. For the request above, the template sees: ```json { "totals": { "line_total": 7039.8, "allowance_total": 100, "charge_total": 0, "tax_basis_total": 6939.8, "tax_total": 1308.99, "grand_total": 8248.79, "prepaid": 0, "due_payable": 8248.79 }, "vat_breakdown": [ { "category": "S", "rate": 7, "basis": 79.8, "tax": 5.59, "exemption_reason": "" }, { "category": "S", "rate": 19, "basis": 6860, "tax": 1303.4, "exemption_reason": "" } ] } ``` The loyalty discount of 100 sits in the 19% group, so its basis is 4,800 + 2,160 − 100 = 6,860. In an e-invoice template, the `money` filter uses the invoice's `currency`, not the template's currency setting. ## Business rules [#business-rules] Before rendering, Druckling checks the payload in two steps: 1. **Shape**, against the template's JSON Schema: required fields, types, date and code formats. A problem answers 422 with code `schema_validation_failed`. 2. **Business rules**, the cross-field rules of EN 16931 and of the format's CIUS. A broken rule answers 422 with code `validation_failed`. The message ends with the rule's ID in parentheses and `field` points at the offending value. Both come back in the same [error format](/docs/concepts/errors). `data.errors` lists every problem found, each with its `field` and `message`, and `rule` for business rules. The failed attempt is recorded as a `failed` document; `data.documentId` is its ID. For example, an XRechnung invoice without a buyer reference: ```json { "defined": false, "code": "UNPROCESSABLE_CONTENT", "status": 422, "message": "The buyer reference is required (for public buyers: their Leitweg-ID) (BR-DE-15)", "data": { "code": "validation_failed", "field": "invoice.buyer_reference", "documentId": "pdf_3Hk9QmZ1xT7pLw2V", "errors": [ { "field": "invoice.buyer_reference", "message": "The buyer reference is required (for public buyers: their Leitweg-ID) (BR-DE-15)", "rule": "BR-DE-15" } ] } } ``` A reverse-charge line without the buyer's VAT ID and exemption reason reports both rules: ```json "errors": [ { "field": "invoice.buyer.vat_id", "message": "Reverse charge needs the buyer's VAT identifier (BR-AE-02)", "rule": "BR-AE-02" }, { "field": "invoice.lines.0.vat_category", "message": "VAT category AE needs an exemption reason or code in vat_exemptions (BR-AE-10)", "rule": "BR-AE-10" } ] ``` The SDKs raise these as validation errors, with every rule in `errors`: ```ts tab="TypeScript" import Druckling, { ValidationError } from "@druckling/sdk"; const druckling = new Druckling(); try { await druckling.documents.create({ template: "xrechnung", data: { invoice } }); } catch (error) { if (!(error instanceof ValidationError)) throw error; for (const problem of error.errors) { console.log(problem.rule, problem.field, problem.message); } } ``` ```python tab="Python" from druckling import Druckling, ValidationError client = Druckling() try: client.documents.create(template="xrechnung", data={"invoice": invoice}) except ValidationError as error: for problem in error.errors: print(problem.rule, problem.field, problem.message) ``` ```php tab="PHP" use Druckling\Exception\ValidationException; use Druckling\Druckling; $druckling = new Druckling(); try { $druckling->documents->create(template: 'xrechnung', data: ['invoice' => $invoice]); } catch (ValidationException $e) { foreach ($e->errors as $problem) { echo $problem->rule, ' ', $problem->field, ' ', $problem->message, PHP_EOL; } } ``` The editor runs the same checks on your sample data and shows broken rules in the preview, for example `E-invoice: A seller contact point (name or department) is required (BR-DE-5)`. Druckling checks the rules that depend on your data. Rules about the XML's structure are guaranteed by the generator. This isn't a full run of the official schematron: if a recipient requires certified validation, check a sample with the validator they name, such as the KoSIT validator for XRechnung or the Peppol BIS validation artifacts. ### EN 16931 rules [#en-16931-rules] These apply to every format. | Rule | Field | Checks | | --- | --- | --- | | `BR-DATE` | any date | The date exists in the calendar (`2026-02-30` fails). A Druckling check, not an EN 16931 rule ID | | `BR-29` | `billing_period.end` | The billing period doesn't end before it starts | | `BR-CO-26` | `seller.vat_id` | The seller has an `id`, `legal_id` or `vat_id` | | `BR-CO-09` | `seller.vat_id`, `buyer.vat_id` | VAT IDs start with a two-letter country prefix | | `BR-27` | `lines.n.net_price` | The net price isn't negative | | `BR-DEC` | `lines.n.price_base_quantity` | The base quantity is positive. A Druckling check | | `BR-DEC-01` | `allowances_charges.n.amount` | Positive, at most 2 decimals | | `BR-33`, `BR-38` | `allowances_charges.n.reason` | Each allowance (BR-33) or charge (BR-38) has a `reason` or `reason_code` | | `BR-DEC-16` | `prepaid_amount` | At most 2 decimals | | `BR-S-05`, `BR-L-05`, `BR-M-05` | `….vat_rate` | Categories `S`, `L` and `M` have a rate above 0 | | `BR-Z-05`, `BR-E-05`, `BR-AE-05`, `BR-IC-05`, `BR-G-05` | `….vat_rate` | Categories `Z`, `E`, `AE`, `K` and `G` have rate 0 | | `BR-S-02`, `BR-Z-02`, `BR-E-02`, `BR-L-02`, `BR-M-02` | `seller.vat_id` | These categories need the seller's VAT ID or tax number | | `BR-AE-02` | `seller.vat_id`, `buyer.vat_id` | Reverse charge needs the seller's VAT ID or tax number and the buyer's VAT ID or legal ID | | `BR-IC-02` | `seller.vat_id`, `buyer.vat_id` | Intra-community supply needs both VAT IDs | | `BR-IC-11` | `delivery_date` | Intra-community supply needs a delivery date or billing period start | | `BR-IC-12` | `delivery.address.country` | Intra-community supply needs the deliver-to country | | `BR-G-02` | `seller.vat_id` | Export needs the seller's VAT ID | | `BR-O-02` | `seller.vat_id` or `buyer.vat_id` | An invoice not subject to VAT carries no VAT IDs | | `BR-E-10`, `BR-AE-10`, `BR-IC-10`, `BR-G-10`, `BR-O-10` | `lines.n.vat_category` | Categories `E`, `AE`, `K`, `G` and `O` have a reason or code in `vat_exemptions` | | `BR-S-10`, `BR-Z-10` | `vat_exemptions.n` | Categories `S` and `Z` have no exemption reason | | `BR-CO-25` | `payment.due_date` | An amount due has a due date or payment terms | | `BR-61` | `payment.iban` | Credit transfers (`30`, `58`) have the payee's IBAN | ### XRechnung rules [#xrechnung-rules] XRechnung adds the German CIUS rules (BR-DE) and the electronic addresses it made mandatory. | Rule | Field | Checks | | --- | --- | --- | | `PEPPOL-EN16931-R020` | `seller.electronic_address` | The seller has an electronic address | | `PEPPOL-EN16931-R010` | `buyer.electronic_address` | The buyer has an electronic address | | `BR-CL-25` | `….electronic_address_scheme` | The scheme is on the CEF EAS code list (`EM` when unset is fine) | | `BR-DE-1` | `payment.means_code` | Payment instructions are given: set the payment means code | | `BR-DE-3`, `BR-DE-4` | `seller.address.city`, `seller.address.postcode` | The seller's city and post code | | `BR-DE-5`, `BR-DE-6`, `BR-DE-7` | `seller.contact.name`, `.phone`, `.email` | A seller contact with name, phone and e-mail | | `BR-DE-8`, `BR-DE-9` | `buyer.address.city`, `buyer.address.postcode` | The buyer's city and post code | | `BR-DE-10`, `BR-DE-11` | `delivery.address.city`, `.postcode` | A deliver-to address with a country also has a city and post code | | `BR-DE-15` | `buyer_reference` | A buyer reference (the Leitweg-ID for public buyers) | | `BR-DE-18` | `payment.terms` | Skonto lines read like `#SKONTO#TAGE=14#PROZENT=2.00#`, in capitals, each followed by a line break | | `BR-DE-23-b` | `payment.mandate_id` or `payment.debited_account` | A credit transfer (`30`, `58`) carries no direct debit details | | `BR-DE-24-a` | `payment.means_code` | Card payments (`48`) aren't supported: use `30`, `58` or `59` | | `BR-DE-25-a` | `payment.mandate_id` | A SEPA direct debit (`59`) has the mandate reference | | `BR-DE-25-b` | `payment.iban` | A SEPA direct debit has no payee IBAN: send the buyer's IBAN as `debited_account` | | `BR-DE-30` | `payment.creditor_id` | A SEPA direct debit has your creditor identifier | | `BR-DE-31` | `payment.debited_account` | A SEPA direct debit has the IBAN to debit | ### Peppol BIS rules [#peppol-bis-rules] | Rule | Field | Checks | | --- | --- | --- | | `PEPPOL-EN16931-R020`, `PEPPOL-EN16931-R010` | `seller.electronic_address`, `buyer.electronic_address` | Both parties have an electronic address (their Peppol participant ID) | | `PEPPOL-EN16931-CL008` | `….electronic_address_scheme` | The scheme is set and on the Peppol EAS code list. `EM` (e-mail) isn't | | `PEPPOL-COMMON-R040` | `….electronic_address`, `….legal_id` | Scheme `0088`: a GLN with a valid GS1 check digit | | `PEPPOL-COMMON-R041` | same | Scheme `0192`: a 9-digit Norwegian organisation number | | `PEPPOL-COMMON-R042` | same | Scheme `0184`: a Danish CVR number (8 digits, optionally prefixed `DK`) | | `PEPPOL-COMMON-R043` | same | Scheme `0208`: a 10-digit Belgian enterprise number with valid check digits | | `PEPPOL-COMMON-R049` | same | Scheme `0007`: a 10-digit Swedish organisation number | | `PEPPOL-COMMON-R050` | same | Scheme `0151`: an 11-digit Australian Business Number | | `PEPPOL-EN16931-R003` | `buyer_reference` | A buyer reference or a purchase order reference | | `PEPPOL-EN16931-R002` | `notes.1` | At most one note, unless both parties are in Germany | | `PEPPOL-EN16931-P0100` | `type_code` | The type is part of Peppol BIS Billing: `389` (self-billing) isn't | | `PEPPOL-EN16931-P0112` | `type_code` | `326` and `384` only between parties in Germany | | `PEPPOL-EN16931-R061` | `payment.mandate_id` | Direct debits (`49`, `59`) have the mandate reference | When both the seller and the buyer are in Germany (`address.country` is `DE` for both), a Peppol invoice also has to pass the German rules from the XRechnung table, reported with Peppol's IDs: `DE-R-001` for BR-DE-1, `DE-R-015` for BR-DE-15, `DE-R-025-1` and `DE-R-025-2` for BR-DE-25-a and -b, and so on. ## Format notes [#format-notes] ### Factur-X and ZUGFeRD [#factur-x-and-zugferd] - The only extra requirement is the PDF standard: PDF/A-3b (the starters' default) or PDF/A-3a. PDF/UA-1 can't be used, because a PDF claims one standard and Factur-X needs PDF/A-3. - Electronic addresses are optional. Without a scheme, an address is written with scheme `EM` (e-mail). - The template's layout is yours, but the numbers come from the payload: bind to the computed fields so the page and `factur-x.xml` agree. ### XRechnung [#xrechnung] A complete XRechnung invoice for a German federal authority. The buyer reference and the buyer's electronic address both carry the Leitweg-ID, with EAS scheme `0204`: ```json title="xrechnung-request.json" { "template": "xrechnung", "data": { "invoice": { "number": "RE-2026-0043", "issue_date": "2026-10-20", "currency": "EUR", "buyer_reference": "04011000-12345-03", "order_reference": "BE-2026-118", "delivery_date": "2026-10-15", "seller": { "name": "Acme Studio GmbH", "legal_id": "HRB 123456 B", "vat_id": "DE123456789", "address": { "line1": "Lindenstraße 12", "postcode": "10969", "city": "Berlin", "country": "DE" }, "electronic_address": "billing@acme-studio.example", "contact": { "name": "Ada Weber", "phone": "+49 30 1234567", "email": "billing@acme-studio.example" } }, "buyer": { "name": "Bundesamt für Beispielwesen", "address": { "line1": "Musterallee 1", "postcode": "53113", "city": "Bonn", "country": "DE" }, "electronic_address": "04011000-12345-03", "electronic_address_scheme": "0204" }, "lines": [ { "name": "Brand identity, phase 2", "quantity": 1, "unit_code": "C62", "net_price": 4800, "vat_category": "S", "vat_rate": 19 }, { "name": "Design system audit", "quantity": 12, "unit_code": "HUR", "net_price": 180, "vat_category": "S", "vat_rate": 19 } ], "payment": { "terms": "Payable within 30 days.\n#SKONTO#TAGE=10#PROZENT=2.00#\n", "due_date": "2026-11-19", "reference": "RE-2026-0043", "means_code": "58", "iban": "DE02120300000000202051", "bic": "BYLADEM1001", "account_name": "Acme Studio GmbH" } } } } ``` The document comes back as XML: ```json { "format": "xml", "content_type": "application/xml", "filename": "xrechnung-8Qw2kLm3.xml", "pages": null, "einvoice": { "format": "xrechnung", "syntax": "ubl", "profile": "XRechnung 3.0", "customization_id": "urn:cen.eu:en16931:2017#compliant#urn:xeinkauf.de:kosit:xrechnung_3.0", "attachment": null } } ``` Things to know: - `buyer_reference` (BT-10) is mandatory. Public buyers give you their Leitweg-ID for it; for other buyers, use the reference they ask for. - Both parties need an `electronic_address`. An e-mail address works with the default scheme `EM`; a Leitweg-ID uses `0204`, a German VAT number `9930`. - The seller needs a full contact (name, phone, e-mail) and both parties a city and post code. - `payment.means_code` is mandatory. For a cash discount (Skonto), add a line like `#SKONTO#TAGE=10#PROZENT=2.00#` to `payment.terms`, followed by a line break. To give the base amount, write `#SKONTO#TAGE=10#PROZENT=2.00#BASISBETRAG=500.00#`. - For a SEPA direct debit, use `means_code: "59"` with `mandate_id`, `creditor_id` and `debited_account`, and leave `iban` out. ### Peppol BIS Billing [#peppol-bis-billing] A Belgian B2B invoice. Both parties are addressed by their enterprise number (EAS `0208`), and the same number is their legal ID: ```json title="peppol-request.json" { "template": "peppol-invoice", "data": { "invoice": { "number": "FAC-2026-0158", "issue_date": "2026-10-20", "currency": "EUR", "buyer_reference": "MKT-2026", "order_reference": "PO-4471", "delivery_date": "2026-10-16", "seller": { "name": "Studio Noord BV", "legal_id": "0123456749", "legal_id_scheme": "0208", "vat_id": "BE0123456749", "address": { "line1": "Kortrijksesteenweg 112", "postcode": "9000", "city": "Gent", "country": "BE" }, "electronic_address": "0123456749", "electronic_address_scheme": "0208", "contact": { "name": "Lotte Peeters", "phone": "+32 9 123 45 67", "email": "invoices@studionoord.example" } }, "buyer": { "name": "Brasserie Lambiek NV", "legal_id": "0987654394", "legal_id_scheme": "0208", "vat_id": "BE0987654394", "address": { "line1": "Grote Markt 7", "postcode": "1000", "city": "Brussel", "country": "BE" }, "electronic_address": "0987654394", "electronic_address_scheme": "0208" }, "lines": [ { "name": "House style design", "quantity": 1, "unit_code": "C62", "net_price": 2400, "vat_category": "S", "vat_rate": 21 }, { "name": "Workshop", "quantity": 2, "unit_code": "DAY", "net_price": 750, "vat_category": "S", "vat_rate": 21 }, { "name": "Printed menu cards", "quantity": 250, "unit_code": "H87", "net_price": 1.84, "vat_category": "S", "vat_rate": 21 } ], "payment": { "terms": "Payment within 30 days of the invoice date.", "due_date": "2026-11-19", "reference": "FAC-2026-0158", "means_code": "58", "iban": "BE68539007547034", "bic": "GKCCBEBB", "account_name": "Studio Noord BV" } } } } ``` Things to know: - Both parties need a Peppol participant ID: `electronic_address` plus its `electronic_address_scheme`. E-mail addresses can't be Peppol endpoints. - For the schemes in the Peppol table (`0088`, `0192`, `0184`, `0208`, `0007`, `0151`), Druckling checks the identifier's format and check digits, in `electronic_address` and in `legal_id`. - Send a `buyer_reference` or an `order_reference`. - Merge notes into one, unless both parties are in Germany. - Self-billed invoices (`389`) aren't part of Peppol BIS Billing. ### Credit notes [#credit-notes] Set `type_code` to `381` and reference the invoice you're crediting. Amounts stay positive: the type code makes it a credit. In UBL syntax (XRechnung, Peppol) Druckling writes a `CreditNote` document instead of an `Invoice`. ```json { "invoice": { "number": "CN-2026-0007", "type_code": "381", "issue_date": "2026-10-27", "preceding_invoice": "RE-2026-0043", "preceding_invoice_date": "2026-10-20", "lines": [ { "name": "Credit: design system audit (2 hours)", "quantity": 2, "unit_code": "HUR", "net_price": 180, "vat_category": "S", "vat_rate": 19 } ], "payment": { "terms": "We'll refund the amount to your account.", "due_date": "2026-11-03", "means_code": "58", "iban": "DE02120300000000202051" } } } ``` The other fields (`currency`, `buyer_reference`, `seller`, `buyer`) are the same as on the original invoice. The starters' layouts switch their heading to Gutschrift or Avoir when `type_code` is `381`. ### Reverse charge and exempt supplies [#reverse-charge-and-exempt-supplies] Categories other than `S`, `Z`, `L` and `M` need an exemption reason. For a German seller invoicing a Belgian business customer under reverse charge: ```json { "buyer": { "name": "Studio Noord BV", "vat_id": "BE0123456749", "address": { "line1": "Kortrijksesteenweg 112", "postcode": "9000", "city": "Gent", "country": "BE" } }, "lines": [ { "name": "Design system audit", "quantity": 12, "unit_code": "HUR", "net_price": 180, "vat_category": "AE", "vat_rate": 0 } ], "vat_exemptions": [ { "category": "AE", "reason": "Reverse charge: VAT is due from the recipient", "code": "VATEX-EU-AE" } ] } ``` The reason appears in the VAT breakdown as `exemption_reason`, so a template can print it next to the 0% line. ## Output formats per template [#output-formats-per-template] The `format` parameter of [`POST /v1/documents`](/docs/api-reference/documents/create) defaults to what the template produces. Asking for another format answers 422 `validation_failed` on `format`; Druckling never switches silently. | Template | Default | Accepted | Rejected | | --- | --- | --- | --- | | No e-invoicing | `pdf` | `pdf`, `png` | `xml` | | Factur-X / ZUGFeRD | `pdf` | `pdf` | `png`, `xml` (the XML lives inside the PDF) | | XRechnung or Peppol BIS | `xml` | `xml` | `pdf`, `png` | To send a readable PDF along with an XRechnung or Peppol invoice, render it from a second e-invoice template set to Factur-X, with the same data. Its PDF shows the same computed totals. ## XML documents [#xml-documents] XRechnung and Peppol documents have `format: "xml"`, `content_type: "application/xml"`, `pages: null`, a file name ending in `.xml` and `einvoice.attachment: null`. Everything else works as for PDFs: download the file from `url`, poll or subscribe to [webhooks](/docs/guides/webhooks) for async renders, and create [share links](/docs/concepts/share-links). Each XML document counts as one document toward your [plan](/docs/concepts/plans-and-limits) in live mode. Rendering an XML e-invoice doesn't run the typesetter: the XML is generated from the payload and the layout plays no part. The `language` parameter is still validated and recorded on the document, but it doesn't change the XML. In a Factur-X PDF, `language` changes the visible pages only; the embedded XML is the same in every language. See [Multi-language templates](/docs/guides/languages). ## Batches of e-invoices [#batches-of-e-invoices] [Batches](/docs/guides/batches) work with e-invoice templates. Every item's invoice is checked against the schema and the business rules before anything renders. If any item fails, nothing is rendered and the 422 names the first problem, for example `field: "items.3.data.invoice.buyer_reference"`, with `data.errors` listing the first invalid items. XRechnung and Peppol batches produce XML files: file names end in `.xml` (a `.pdf` in `filename_pattern` or an item's `filename` becomes `.xml`), and the batch ZIP contains the XML files. ```bash curl https://druckling-nine.vercel.app/v1/batches \ -H "Authorization: Bearer $DRUCKLING_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "template": "xrechnung", "filename_pattern": "{{invoice.number}}.xml", "items": [ { "data": { "invoice": { "number": "RE-2026-0043", "…": "…" } } }, { "data": { "invoice": { "number": "RE-2026-0044", "…": "…" } } } ] }' ``` ## Test before you go live [#test-before-you-go-live] Render with a `dr_test_…` key while you build your integration: [test-mode](/docs/concepts/test-mode) documents go through exactly the same validation and generation and don't count toward your quota. Check a few generated files with the validators your recipients use before switching to a live key. Combine Factur-X with PDF/A-3a for an accessible e-invoice. Render a month of invoices in one request. The error format and every error code. # Embedded editor (/docs/guides/embedded-editor) > Let your users edit a Druckling template inside your own product, in a white-label editor that you frame on your pages. The embedded editor puts Druckling's template editor inside your product, so your users can change their own invoice, certificate or ticket layout without a Druckling account. Your backend creates a short-lived session for one template, your frontend shows it in an iframe, and the editor tells your page what happens over `postMessage`. ## How it works [#how-it-works] 1. **Once:** allow the origins of your app in **Settings › Embed**. 2. **When a user opens the editor:** your backend creates a session with `POST /v1/embed_sessions` and passes the returned `url` to that user's browser. 3. **In the browser:** your page mounts the `url` in an iframe, with `@druckling/embed` or a plain ` ``` ```js title="template-editor.js" const iframe = document.getElementById("template-editor"); const { url } = await fetch("/api/template-editor", { method: "POST" }).then((r) => r.json()); const editorOrigin = new URL(url).origin; window.addEventListener("message", (event) => { if (event.origin !== editorOrigin || event.source !== iframe.contentWindow) return; const message = event.data; if (message?.source !== "druckling-embed" || message.protocol !== 1) return; if (message.type === "error" && message.code === "session_expired") showReopenButton(); }); iframe.addEventListener("load", () => { iframe.contentWindow.postMessage({ source: "druckling-embed", protocol: 1, type: "connect", closeButton: true }, editorOrigin); }); iframe.src = url; ``` Every message carries `source: "druckling-embed"` and `protocol: 1`; the events are the ones listed above. Your page can send two commands: - `connect`, with an optional `closeButton: true` for the **Done** button. Send it when the iframe loads. - `save`, with an optional `requestId` (up to 100 characters). The editor answers with `saved` or `error` carrying the same `requestId`. The editor only sends events once it knows which page frames it and that the page's origin is allowed. Most browsers report the framing page's origin to it; where they don't, it uses the referrer (hence `referrerpolicy="origin"`) or your `connect` message. Events from before that are held back and delivered once it's connected. ### Renew an expired session [#renew-an-expired-session] Sessions can't be extended. When `session_expired` arrives, create a new session and mount it in place of the old one. The draft is saved as the user edits, so the new session opens where they left off. ```ts title="template-editor.ts" import { mountEditor } from "@druckling/embed"; async function openEditor() { const { url } = await fetch("/api/template-editor", { method: "POST" }).then((r) => r.json()); const editor = mountEditor({ url, container: "#template-editor", height: "80vh", onError: ({ code }) => { if (code !== "session_expired") return; editor.destroy(); void openEditor(); }, }); } void openEditor(); ``` If users tend to edit for longer, raise `expires_in` (up to an hour), or use `expiresAt` from the `ready` event to remind them before the session ends. ## 4. Revoke the session on sign-out [#4-revoke-the-session-on-sign-out] Sessions end on their own at `expires_at`. To end one early, for example when the user signs out of your product, revoke it with the id you stored. The open editor reports `session_revoked` on its next request, such as the next autosave. Revoking twice is fine. ```bash tab="cURL" curl -X DELETE https://druckling-nine.vercel.app/v1/embed_sessions/emb_8Qw2kLm3nP0aB1cD \ -H "Authorization: Bearer $DRUCKLING_API_KEY" ``` ```ts tab="TypeScript" await druckling.embedSessions.revoke(req.session.editorSessionId); ``` ```python tab="Python" client.embed_sessions.revoke(session["editor_session_id"]) ``` ```php tab="PHP" $druckling->embedSessions->revoke($_SESSION['editor_session_id']); ``` The response is the session with `status: "revoked"` and `url: null`. Revoke with a full-access key of the same mode as the key that created the session; a key of the other mode gets `404`. See [Revoke an embedded editor session](/docs/api-reference/embedded-editor/revoke). ## What a session can do [#what-a-session-can-do] An editor session works on its own template only: - **Read** the template and its draft. - **Edit** the draft. Changes save automatically and never affect renders until a new version is published. - **Preview** the page live, and open a **Test PDF** of the draft in a new tab. Test PDFs don't create documents. - **Publish** a new version, only with `permissions.publish: true`. From then on, API requests for `version: "latest"` render it. Pin a `version` in your render requests if you want to review changes first. - **Use the AI assistant**, only with `permissions.assistant: true` on Pro or Business. In the embedded editor the assistant works on that template only and doesn't take image attachments. It can't open other templates (even ones that exist), documents, API keys, webhooks, billing, team or workspace settings, and it can't create sessions. The editor has no dashboard navigation, so there's no way out of the template. Without `permissions.publish`, your users' changes stay in the draft until someone on your team publishes it in the dashboard. Druckling sends no webhook when a template is published; the `published` event is how your page finds out. ## Security model [#security-model] - **The token travels in the URL fragment.** The `url` carries the session token after `#token=`, and browsers never send the fragment to any server. The editor reads it once, removes it from its address and history, keeps it in memory and sends it as an `Authorization` header. Druckling stores only a SHA-256 hash of the token. - **The session id isn't a secret.** `?session=emb_…` only picks the page's `frame-ancestors`. A token that doesn't belong to that session is rejected. - **Framing is restricted.** The editor page answers with `Content-Security-Policy: frame-ancestors 'self'` plus your allowed origins (`'self'` is Druckling's own dashboard, for the preview). An unknown session gets `frame-ancestors 'none'`. - **Messages go to your origin only.** The editor posts messages to the exact origin of the framing page, never `*`, and only once that origin is allowed. It accepts commands only from the parent window at that origin. Check `event.origin` and `event.source` the same way on your side, or let `@druckling/embed` do it. - **No cookies.** The editor doesn't use cookies, so browsers that block third-party cookies show it as well. Requests carrying an editor token reach only the editor's own operations, whatever cookies come with them. - **Short-lived by default.** 30 minutes unless you set `expires_in`, at most an hour, and revocable at any time. - **Your API key stays on your server.** Create sessions from your backend after your own sign-in check, and hand the `url` only to the user it's for. ## Logs and version history [#logs-and-version-history] **Developers › Logs** shows what your users do in the editor: - `POST /v1/embed_sessions` and `DELETE /v1/embed_sessions/{id}` appear with the API key that made them and "for" the user you passed. - Requests from the editor itself (opening the session, saving the draft, publishing, test PDFs and any request that failed) appear with **Embedded editor** in the API key column and "for" the user's `name` (or `id`), or the session id when you didn't pass a `user`. Successful template loads and previews aren't logged. Published versions record who published them as `embed:` plus your user's `id` (for example `embed:user_42`), or plus the session id without a `user`. You see it in the template's version history. ## Test and live keys [#test-and-live-keys] A session takes the mode of the key that created it, shown as `test_mode`. Its requests appear in **Developers › Logs** when the dashboard's **Test mode** matches. Test mode separates documents and usage, not templates. A session created with a `dr_test_…` key edits the same template your live renders use, and with `permissions.publish: true` it publishes real versions. Experiment on a copy of the template, or keep publishing off while you test. See [Test mode](/docs/concepts/test-mode) for what else test keys change. ## Theming [#theming] Each session can match the brand of the customer it's for: - `theme.mode`: `light` (default), `dark`, or `system`, which follows the user's operating system and switches live when they change it. - `theme.accent`: a hex color that becomes the editor's primary color: buttons, focus rings, selections and highlights. Text on it is black or white, whichever reads better. `#0f766e` and `#0F766E` are the same color, and `#abc` is stored as `#aabbcc`. Without an accent, the editor keeps Druckling's own colors. ## Limits [#limits] | Limit | Value | | --- | --- | | Session length | 30 minutes by default, 60 seconds to 1 hour | | New sessions | 60 a minute per workspace | | Allowed origins | 20 per workspace | | Requests from one editor session (saves, previews) | 600 a minute | | Assistant turns in one editor session | 10 a minute | ## Troubleshooting [#troubleshooting] The browser blocked the frame because of `frame-ancestors`. Check that: - The exact origin of your page is in **Settings › Embed**: scheme, host and port. `https://www.example.com` and `https://example.com` are different, and `https://*.example.com` doesn't cover `https://example.com`. - You pass the `url` unchanged. Without its `?session=` the page can't be framed anywhere. - The session is recent. Sessions are deleted a day or two after they expire, and their URLs can't be framed after that. Create a new one. - Your own Content Security Policy allows the frame, e.g. `frame-src https://druckling-nine.vercel.app`. The workspace has no allowed origin. An owner or admin adds one in **Settings › Embed**. The API key is render-only. Create a full-access key in **Developers › API keys**. The token is missing or doesn't match the session in the URL. Something between your backend and the iframe dropped the `#token=…` fragment or changed the URL, for example a redirect or a router that rewrites links. Pass the `url` exactly as the API returned it. - Compare `event.origin` with Druckling's origin (`new URL(url).origin`), not your own. - Your page's origin must be allowed in **Settings › Embed**; the editor never posts to other origins. - With a plain iframe, set `referrerpolicy="origin"` and send the `connect` command when the iframe loads. The editor shows **Publish** only with `permissions.publish: true`, and the assistant only with `permissions.assistant: true` on Pro or Business. The `ready` event and the create response tell you what the session got. The editor didn't answer, usually because it hasn't finished loading or its session already ended. Wait for `ready` before calling `save()`. ## Next steps [#next-steps] Every field of the request and the response. Drafts, published versions and how renders pick a version. Get notified when documents rendered from your users' templates are ready. # Multi-language templates (/docs/guides/languages) > Render one template in several languages, with translated texts and number, date and currency formats that follow the language. A template can print in more than one language. It has a default language and up to 30 more, and each render picks one with the `language` parameter. Layout, styles, variables and sample data are shared by all languages: only the template's texts are translated, so a design change applies to every language at once. ## How it works [#how-it-works] - **The default language** holds the texts you see in the blocks. New blank templates start in English (`en`); the e-invoice starters start in German or French. - **Other languages** store translations of single texts. A text you haven't translated yet prints in the default language, so a half-translated template still renders. - **Each render** uses one language: the default, or the one you pass as `language`. Numbers, dates, currency amounts, hyphenation and the PDF's declared language follow it. ## Supported languages [#supported-languages] Languages are two-letter ISO 639-1 codes. The editor offers the 24 official EU languages and six more: | Group | Codes | | --- | --- | | EU languages | `bg` Bulgarian, `cs` Czech, `da` Danish, `de` German, `el` Greek, `en` English, `es` Spanish, `et` Estonian, `fi` Finnish, `fr` French, `ga` Irish, `hr` Croatian, `hu` Hungarian, `it` Italian, `lt` Lithuanian, `lv` Latvian, `mt` Maltese, `nl` Dutch, `pl` Polish, `pt` Portuguese, `ro` Romanian, `sk` Slovak, `sl` Slovenian, `sv` Swedish | | More languages | `ca` Catalan, `is` Icelandic, `lb` Luxembourgish, `nb` Norwegian Bokmål, `tr` Turkish, `uk` Ukrainian | A template can have up to 31 languages: the default plus 30 translations. ## Add and translate a language [#add-and-translate-a-language] ### Add the language [#add-the-language] Open the template with **Open editor**. In the toolbar above the page, open the language menu (it shows the current language, for example **English**) and choose a language under **Add a language…**. ### Translate the texts [#translate-the-texts] Select the language in the same menu. The page now shows that language, and a note at the top of the right-hand panel says you're editing it: texts you change are saved as translations, while layout and style changes still apply to every language. Edit texts on the page or in the inspector as usual. **Back to English** (or your default language) in that note returns to the default texts. The menu shows each language's progress, such as `12/30`. Open **untranslated** under a language to list the texts still missing and jump to each one. You can also ask Druck, the AI assistant, for a translation, for example "Make a French version". It proposes the translated texts as one change, which you **Apply** or **Discard**. ### Publish [#publish] Translations are part of the template. Publish a new version so that API renders can use the language. The editor warns about texts that aren't translated yet; they don't block publishing, because they print in the default language. A translation with a broken binding, such as a misspelled variable, is an error and has to be fixed first. Each language's **⋯** menu has two more actions: - **Make default** turns the language into the default: its translations become the block texts, and the previous default's texts become a translation. Texts it hadn't translated stay as they are. - **Remove** deletes the language and all its translations. The **Language** field under **Document** › **Typography** only relabels the default language, for example when the texts are German but the template is set to English. It doesn't translate anything. ## What gets translated [#what-gets-translated] These texts can differ per language: - The document title and the watermark text - Text and heading blocks - Table column headers and cells, totals row labels and values, and the text shown for an empty table - Image alt text - Chart titles - Signature labels and signer names - The page number format, for example `Page {page} of {total}` Everything else is shared: layout, styles, fonts, page setup, images, QR code and barcode values, variables, sample data and the template's currency. Texts without words, such as a cell that only contains `{{item.qty}}`, print the same in every language and don't count as untranslated. Your payload isn't translated either. Values like line item descriptions print exactly as you send them, so send them in the language you render. A translated text keeps its bindings, filters and formatting. In German, `No. {{invoice.number}}` might become `Nr. {{invoice.number}}`, and `**{{invoice.due_date | date}}**` stays as it is, because the date filter already follows the language. ## What follows the language [#what-follows-the-language] Filters format values for the render language: | Language | `money` (USD) | `money` (EUR) | `number:2` | `date` | | --- | --- | --- | --- | --- | | English (`en`) | $4,800.00 | €1,234.50 | 1,234.50 | Nov 22, 2026 | | German (`de`) | 4.800,00 $ | 1.234,50 € | 1.234,50 | 22.11.2026 | | French (`fr`) | 4 800,00 $ | 1 234,50 € | 1 234,50 | 22/11/2026 | | Dutch (`nl`) | 4.800,00 $ | 1.234,50 € | 1.234,50 | 22-11-2026 | | Italian (`it`) | 4.800,00 $ | 1.234,50 € | 1.234,50 | 22/11/2026 | | Polish (`pl`) | 4.800,00 $ | 1.234,50 € | 1.234,50 | 22.11.2026 | - **Decimal separator.** English, Irish and Maltese use a decimal point and a comma between thousands. The other languages use a decimal comma, with a point between thousands, or a narrow space in French. - **Currency position.** With a decimal comma, the symbol follows the amount. Otherwise it comes first, separated by a space for letter codes such as `CHF 1,234.50`. - **Dates.** English prints `Nov 22, 2026`; French, Spanish, Italian and Portuguese `22/11/2026`; Dutch `22-11-2026`; all others `22.11.2026`. A pattern given to the `date` filter overrides this. - **Hyphenation.** With **Hyphenate** switched on under **Document** › **Typography**, words are hyphenated with the render language's rules. - **PDF language.** The PDF declares the render language, so screen readers pronounce it correctly. See [Accessible PDFs](/docs/guides/accessible-pdfs). The currency itself doesn't change with the language. It comes from the template's **Currency** setting, the code you pass to the filter (`{{totals.amount | money:EUR}}`), or, in e-invoice templates, the invoice's `currency`. See [Template strings](/docs/concepts/template-strings) for the filters. ## Render in a language [#render-in-a-language] Pass `language` to [`POST /v1/documents`](/docs/api-reference/documents/create). This renders the `invoice-standard` template in German, once you've added and published German for it: ```bash tab="cURL" curl https://druckling-nine.vercel.app/v1/documents \ -H "Authorization: Bearer $DRUCKLING_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "template": "invoice-standard", "language": "de", "data": { "invoice": { "number": "INV-2041", "due_date": "2026-11-22" }, "customer": { "name": "Northwind GmbH", "address": "Hafenweg 3, 20457 Hamburg" }, "line_items": [ { "description": "Design-System-Audit", "qty": 12, "rate": 180, "amount": 2160 } ], "totals": { "subtotal": 2160, "tax": 172.8, "amount": 2332.8 } } }' ``` ```ts tab="TypeScript" import Druckling from "@druckling/sdk"; const druckling = new Druckling(); // reads DRUCKLING_API_KEY const document = await druckling.documents.create({ template: "invoice-standard", language: "de", data: { invoice: { number: "INV-2041", due_date: "2026-11-22" }, customer: { name: "Northwind GmbH", address: "Hafenweg 3, 20457 Hamburg" }, line_items: [{ description: "Design-System-Audit", qty: 12, rate: 180, amount: 2160 }], totals: { subtotal: 2160, tax: 172.8, amount: 2332.8 }, }, }); console.log(document.language); // de ``` ```python tab="Python" from druckling import Druckling client = Druckling() # reads DRUCKLING_API_KEY document = client.documents.create( template="invoice-standard", language="de", data={ "invoice": {"number": "INV-2041", "due_date": "2026-11-22"}, "customer": {"name": "Northwind GmbH", "address": "Hafenweg 3, 20457 Hamburg"}, "line_items": [{"description": "Design-System-Audit", "qty": 12, "rate": 180, "amount": 2160}], "totals": {"subtotal": 2160, "tax": 172.8, "amount": 2332.8}, }, ) print(document.language) # de ``` ```php tab="PHP" documents->create( template: 'invoice-standard', language: 'de', data: [ 'invoice' => ['number' => 'INV-2041', 'due_date' => '2026-11-22'], 'customer' => ['name' => 'Northwind GmbH', 'address' => 'Hafenweg 3, 20457 Hamburg'], 'line_items' => [['description' => 'Design-System-Audit', 'qty' => 12, 'rate' => 180, 'amount' => 2160]], 'totals' => ['subtotal' => 2160, 'tax' => 172.8, 'amount' => 2332.8], ], ); echo $document->language; // de ``` How `language` is resolved: - **Left out**, the render uses the template's default language. - **Case and region don't matter.** `DE`, `de-AT` and `de_CH` all render German. The document records the template's language, `de`, in its `language` field. - **Missing translations fall back** to the default language, text by text. - **A language the template doesn't have** answers 422 `validation_failed` on `language`, before anything is rendered or recorded: ```json { "defined": false, "code": "UNPROCESSABLE_CONTENT", "status": 422, "message": "The template has no \"pl\" version; its languages are en (default), de, fr", "data": { "code": "validation_failed", "field": "language", "language": "pl", "available": ["en", "de", "fr"] } } ``` The language belongs to a published version, like the rest of the template. A request for `"version": 3` can use the languages version 3 had. ### Find a template's languages [#find-a-templates-languages] [`GET /v1/templates/{slug}`](/docs/api-reference/templates/get) and the [template list](/docs/api-reference/templates/list) return `language`, the default, and `languages`, every language the template renders in with the default first. They come from the latest published version, or from the draft if the template was never published. ```json { "slug": "invoice-standard", "language": "en", "languages": ["en", "de", "fr"] } ``` The template's page in the dashboard (**Templates** › your template) also has a language picker for its API example. ## Batches [#batches] [Batches](/docs/guides/batches) take a `language` for every item and a `language` per item that overrides it: ```bash curl https://druckling-nine.vercel.app/v1/batches \ -H "Authorization: Bearer $DRUCKLING_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "template": "invoice-standard", "language": "de", "items": [ { "data": { "…": "…" } }, { "data": { "…": "…" }, "language": "fr" }, { "data": { "…": "…" }, "language": "en" } ] }' ``` All languages are checked before anything is stored. An unknown one rejects the whole batch with 422 `validation_failed` on `language` or on the item's field, such as `items.1.language`. Each document in the batch records its own `language`. ## E-invoices [#e-invoices] For [e-invoices](/docs/guides/e-invoicing), `language` only affects what people read: - **Factur-X and ZUGFeRD.** The visible pages follow the language; the embedded `factur-x.xml` is the same in every language. - **XRechnung and Peppol BIS.** The XML doesn't change with the language. `language` is still checked against the template's languages and recorded on the document. Texts from the payload, such as line names, notes and payment terms, appear as you send them in both the PDF and the XML. ## Accessibility [#accessibility] In a template with PDF/UA-1 or PDF/A-3a, the accessibility checks run for every language, since a translation can leave a heading or an alt text empty. Problems in another language are prefixed with its name, for example `German: PDF/UA: headings can't be empty`. Translate the document title and alt texts along with the other texts. See [Accessible PDFs](/docs/guides/accessible-pdfs). Bindings and filters such as money, date and number. Preview each language as an image. # MCP server (/docs/guides/mcp) > Connect Claude, Cursor, VS Code, n8n and other MCP clients to Druckling so AI agents can render documents and build templates with your API key. Druckling hosts a [Model Context Protocol](https://modelcontextprotocol.io) server, so AI agents can work with your templates and documents directly. An agent can look up a template's data contract, render a PDF and hand you the link, or build a new template from a starter, preview it with Typst and publish it, using the same validated edit operations as the editor. There's nothing to install or run: point your MCP client at the endpoint and authenticate with an API key. ## Endpoint [#endpoint] ```txt https://druckling-nine.vercel.app/api/mcp ``` - **Transport:** Streamable HTTP. - **Authentication:** a Druckling API key, as `Authorization: Bearer dr_test_…` or in an `x-api-key` header. The server doesn't offer OAuth sign-in; clients that can't send a header can connect through `mcp-remote` (see [Claude Desktop](#set-up-your-client)). - **Per request:** every request is authenticated with the key it carries, so revoking a key in **Developers › API keys** cuts the agent off right away. **Settings › AI tools (MCP)** in the dashboard shows the endpoint and ready-to-paste snippets for the clients below. ## Choose an API key [#choose-an-api-key] The key decides what the agent can do. Tools the key isn't allowed to use aren't listed at all, so the agent never plans around them. | Key | Tools | | --- | --- | | **Render only** | `render_document`, `get_document`, `list_documents` | | **Full access** | All of the above, plus `list_templates`, `get_template`, `template_reference`, `create_template`, `get_template_draft`, `edit_template`, `preview_template`, `publish_template` | Start with a **test key** (`dr_test_…`): test renders are free and don't count toward your quota. Switch to a live key when the agent's output looks right. Create keys in **Developers › API keys**; see [Authentication](/docs/authentication) and [Test mode](/docs/concepts/test-mode). A render-only key can't list or read templates, so tell the agent which template slug to use and what data it takes. Test mode separates documents and usage, not templates. A full-access test key can edit and publish the same templates your live renders use. Give an agent a render-only key unless you want it to change templates. ## Set up your client [#set-up-your-client] Replace `dr_test_…` with your own key. Run this in a terminal. Add `--scope user` to use it in every project. ```bash claude mcp add --transport http druckling https://druckling-nine.vercel.app/api/mcp --header "Authorization: Bearer dr_test_…" ``` To share the server with your team, commit a `.mcp.json` instead. Each person sets `DRUCKLING_API_KEY` in their environment: ```json title=".mcp.json" { "mcpServers": { "druckling": { "type": "http", "url": "https://druckling-nine.vercel.app/api/mcp", "headers": { "Authorization": "Bearer ${DRUCKLING_API_KEY}" } } } } ``` **Custom connector.** In Claude (desktop or claude.ai), open **Settings › Connectors › Add custom connector**, paste the endpoint, choose **No sign-in** and add the request header `authorization` with the value `Bearer dr_test_…`. Request headers on custom connectors aren't available to every Claude organization yet. **Without request headers**, add the server to `claude_desktop_config.json` through [`mcp-remote`](https://www.npmjs.com/package/mcp-remote), which needs Node.js, then restart Claude Desktop: ```json title="claude_desktop_config.json" { "mcpServers": { "druckling": { "command": "npx", "args": ["-y", "mcp-remote", "https://druckling-nine.vercel.app/api/mcp", "--header", "Authorization:${AUTH_HEADER}"], "env": { "AUTH_HEADER": "Bearer dr_test_…" } } } } ``` Keep `Authorization:${AUTH_HEADER}` without spaces: it works around an argument bug on Windows. Add the server to `~/.cursor/mcp.json` (all projects) or `.cursor/mcp.json` (this project): ```json title="~/.cursor/mcp.json" { "mcpServers": { "druckling": { "url": "https://druckling-nine.vercel.app/api/mcp", "headers": { "Authorization": "Bearer ${env:DRUCKLING_API_KEY}" } } } } ``` `${env:DRUCKLING_API_KEY}` keeps the key out of the file. You can also paste the key in its place. Add the server to `.vscode/mcp.json`. With an input, VS Code asks for the key the first time the server starts instead of storing it in the file: ```json title=".vscode/mcp.json" { "inputs": [ { "type": "promptString", "id": "druckling-api-key", "description": "Druckling API key", "password": true } ], "servers": { "druckling": { "type": "http", "url": "https://druckling-nine.vercel.app/api/mcp", "headers": { "Authorization": "Bearer ${input:druckling-api-key}" } } } } ``` On an **AI Agent** node, add the **MCP Client Tool** and fill in: | Field | Value | | --- | --- | | Endpoint | `https://druckling-nine.vercel.app/api/mcp` | | Server Transport | HTTP Streamable | | Authentication | Bearer Auth, with the key as the token (or Header Auth: `x-api-key` = `dr_test_…`) | | Tools to Include | All, or Selected, e.g. only `render_document` | Outside an agent, the **MCP Client** node calls one tool directly with the same settings. For workflows that don't involve an agent, the [Druckling n8n node](/docs/guides/n8n) is usually simpler. Any MCP client that supports Streamable HTTP and custom headers works with two settings: - **URL:** `https://druckling-nine.vercel.app/api/mcp` - **Header:** `Authorization: Bearer dr_test_…` (or `x-api-key: dr_test_…`) For a client that only runs local (stdio) servers, run the server through `mcp-remote` as shown for Claude Desktop: ```bash npx -y mcp-remote https://druckling-nine.vercel.app/api/mcp --header "Authorization:${AUTH_HEADER}" ``` with `AUTH_HEADER` set to `Bearer dr_test_…` in the client's environment for the server. ## Tools [#tools] The server exposes tools only, no resources or prompts. When a client connects, the server also sends instructions that tell the agent the key's mode and access level and the workflow below. | Tool | What it does | Inputs | Key | | --- | --- | --- | --- | | `render_document` | Renders a published template and returns the document id, status, page count and a time-limited signed download URL. E-invoice templates produce their Factur-X PDF or XRechnung or Peppol XML. | `template`, `data`; optional `version`, `filename`, `format` (`pdf`, `png`, `xml`), `async`, `language` | Render only | | `get_document` | Gets a document: status, pages, a fresh signed URL, the error with its field if it failed, and its timeline. | `id` | Render only | | `list_documents` | Lists recent documents of the key's mode, newest first. | optional `status`, `template`, `limit` (1–100, default 20), `cursor` | Render only | | `list_templates` | Lists templates with slug, name, status, latest version, required fields and languages. | optional `search`, `status` (`draft`, `published`) | Full access | | `get_template` | Gets a template's data contract: JSON Schema, required fields, complete `sample_data`, languages and published versions. | `template`; optional `version` | Full access | | `template_reference` | Explains template strings, filters, variables, every block type and the edit operation formats. | none | Full access | | `create_template` | Creates a draft, blank or from a starter such as `invoice-standard` or `packing-slip`. | `name`; optional `starter` | Full access | | `get_template_draft` | Reads the editable draft: the document JSON with block ids, its `draft_revision`, validation issues and an outline. | `template` | Full access | | `edit_template` | Applies edit operations to the draft, in order and atomically: one invalid op rejects the whole call. | `template`, `base_revision`, `ops` (1–200) | Full access | | `preview_template` | Compiles the draft with Typst without saving anything: page count, the pages each block lands on, errors and warnings per block. | `template`; optional `data`, `language` | Full access | | `publish_template` | Publishes the draft as a new immutable version, after checking for validation errors and a clean Typst render. | `template`, `base_revision`; optional `note` | Full access | Tools that only read are annotated as read-only, and `publish_template` as destructive, so clients that support annotations can auto-approve reads and ask before publishing. ### How agents use them [#how-agents-use-them] - **Render a document:** `list_templates` → `get_template` → `render_document` with `data` that matches the schema. For large documents, `render_document` with `async: true`, then `get_document` until the status is `rendered` or `failed`. - **Build or change a template:** `template_reference` once → `create_template` → `get_template_draft` → `edit_template` → `preview_template` → `publish_template` → `render_document`. Drafts never affect renders until they're published. Every `edit_template` and `publish_template` call passes the `draft_revision` it last read as `base_revision`; if someone changed the draft in the meantime, the call fails with `stale_revision` and the agent re-reads the draft. Failed calls come back as tool errors the agent can act on: the message, the error `code` and `field`, every offending field (for example each schema mismatch or broken e-invoice rule), and a hint for the next step. See [Errors](/docs/concepts/errors) for the codes. ## Example prompts [#example-prompts] - "Which templates do I have, and what data does invoice-standard need?" - "Render invoice-standard for Northwind Ltd., 12 Pier St, Leeds: invoice INV-2042, due November 22, 12 hours of design system audit at 180 and one brand workshop at 640, plus 8% tax. Send me the link." - "Render the invoice again in German." - "Which documents failed today, and why?" - "Create a packing slip from the packing-slip starter with our return address in the footer. Preview it with 40 items to check the page breaks, then publish it." ## Limits [#limits] - **60 seconds per request.** A synchronous `render_document` or a `preview_template` has to finish within that time; render large documents with `async: true`. - **Rate limit.** Every MCP request, including the client's `initialize` and `tools/list`, is authenticated with the key and counts toward its rate limit of 120 requests a minute, shared with `/v1`. - **Quota.** Live renders count toward your plan's monthly documents; test renders don't. See [Plans and limits](/docs/concepts/plans-and-limits). Tool calls appear in **Developers › Logs** next to your API requests, with method `MCP`, the endpoint `/api/mcp/` and an HTTP-style status (for example `422` for a payload that doesn't match the schema). ## Security [#security] - **Use a test key while trying it out**, and a **render-only key** for agents that only need to render: they can't see or change templates. - **Keep keys out of committed files** with environment variables or input prompts, as in the snippets above. - **Signed URLs are links anyone can open** until they expire. They end up in the agent's conversation, so treat transcripts accordingly. See [Documents](/docs/concepts/documents). - **Your MCP client's AI provider sees the tool calls**, including the payload data you render. Druckling's EU-only, zero-retention inference applies to Druck, the AI assistant built into Druckling, not to the client you connect. - **Revoke a key** in **Developers › API keys** to cut an agent off. The next request fails with `401`. ## Next steps [#next-steps] How a template's JSON Schema and sample data are derived. Render documents in workflows with the Druckling node. The API request behind render_document. # n8n (/docs/guides/n8n) > Render Druckling documents in n8n workflows and start workflows when a document is rendered, fails or expires. The `n8n-nodes-druckling` community package adds two nodes to [n8n](https://n8n.io): **Druckling**, which renders documents and reads documents and templates, and **Druckling Trigger**, which starts a workflow when a document is rendered, fails or expires. Use them to turn orders, form submissions or spreadsheet rows into invoices, certificates and tickets, and to send the PDF on. ## Install the package [#install-the-package] `n8n-nodes-druckling` isn't published to npm yet, so installing it by name under **Settings › Community Nodes** doesn't work yet. Install it from the Druckling source repository on a self-hosted n8n, as below. On n8n Cloud, which only offers verified community nodes, connect through the [MCP Client Tool](/docs/guides/mcp) instead. ### Build the package [#build-the-package] ```bash git clone https://github.com/vulpery/druckling.git cd druckling/src/integrations/n8n-nodes-druckling npm install npm run build npm pack ``` `npm pack` writes `n8n-nodes-druckling-0.1.0.tgz`. ### Install it into n8n [#install-it-into-n8n] Install the tarball into n8n's nodes folder: ```bash mkdir -p ~/.n8n/nodes cd ~/.n8n/nodes npm install /path/to/n8n-nodes-druckling-0.1.0.tgz ``` If n8n runs in Docker, copy the tarball into the container and install it there, in the `.n8n/nodes` folder on n8n's persistent volume: ```bash docker cp n8n-nodes-druckling-0.1.0.tgz n8n:/tmp/ docker exec -it n8n sh -c "mkdir -p ~/.n8n/nodes && cd ~/.n8n/nodes && npm install /tmp/n8n-nodes-druckling-0.1.0.tgz" ``` ### Restart n8n [#restart-n8n] After a restart, **Druckling** and **Druckling Trigger** appear in the nodes panel. The package is built and tested against n8n 2.x (`n8n-workflow` 2.43, Node.js 24). It uses resource locators, resource mappers and AI tool support, which older n8n 1.x releases may lack. ## Add your credentials [#add-your-credentials] Create a **Druckling API** credential: | Field | Value | | --- | --- | | **API Key** | A key from **Developers › API keys**: `dr_test_…` while you build, `dr_live_…` in production. | | **Base URL** | `https://druckling-nine.vercel.app` (the default). A trailing `/v1` is fine. | The key is sent as `Authorization: Bearer `. The credential test calls `GET /v1/templates`. Use a **full-access** key. The credential test, the template list, **Map Template Fields** and the language list all read your templates, and the trigger manages webhook endpoints; render-only keys can do neither. With a render-only key the credential test fails, and only the **Document** operations work, with the template entered **By Slug** and the data as JSON. See [Authentication](/docs/authentication). Test keys render documents that never count toward your plan's usage. Webhook endpoints, documents and events belong to the mode of the key, so a workflow with a test key sees only test documents. See [Test mode](/docs/concepts/test-mode). ## Druckling node [#druckling-node] The Druckling node has two resources, **Document** and **Template**. It can also be used as a tool by n8n's **AI Agent**, for example to look up a template's schema and render a document from data the agent collected. ### Document › Render [#document--render] Renders a published template, like [`POST /v1/documents`](/docs/api-reference/documents/create). | Parameter | Description | | --- | --- | | **Template** | **From List** (drafts are marked: only published templates render) or **By Slug**, e.g. `invoice-standard`. | | **Data Mode** | **JSON**: one object that matches the template's schema, e.g. the expression `{{ $json }}`. **Map Template Fields**: n8n loads the template's variables and you fill each from a value or expression; arrays such as `line_items` take a JSON array. | | **Download PDF** | Downloads the rendered file into a binary field. See [Binary output](#binary-output). | | **Put Output File in Field** | Name of that binary field. Default `data`. | | **Options › Async** | Queues the render and returns right away with status `queued`. Nothing is downloaded; pick up the result with the trigger or **Get**. | | **Options › Filename** | File name of the document, e.g. `INV-2042.pdf`. | | **Options › Language** | One of the template's languages, from a list or an expression such as `{{ $json.customer.language }}`. Default: the template's default language. See [Languages](/docs/guides/languages). | | **Options › Version** | A published version to render instead of the latest. | The node doesn't offer PNG output or batches. For those, call the API with an **HTTP Request** node (see [PNG output](/docs/guides/png-output) and [Batches](/docs/guides/batches)). ### Document › Get [#document--get] Gets a document by **Document ID** (e.g. `pdf_WvSdGvCMqjllJNqy`, or `{{ $json.data.id }}` after the trigger), with a fresh signed URL. Turn on **Download PDF** to fetch the file. See [Get a document](/docs/api-reference/documents/get). ### Document › Get Many [#document--get-many] Lists documents, newest first, one item per document. Use **Return All** or **Limit** (default 50), and filter by **Status** (`queued`, `rendering`, `rendered`, `failed`, `expired`) or **Template Slug**. See [List documents](/docs/api-reference/documents/list). ### Template › Get and Get Many [#template--get-and-get-many] **Get** returns one template with its `json_schema`, `sample_data`, `required_fields`, default `language` and `languages`; it's the quickest way to see which data a template needs. **Get Many** returns the workspace's templates (all, or up to **Limit**) with their status, latest version and languages. See [Get a template](/docs/api-reference/templates/get). ### Binary output [#binary-output] With **Download PDF** on, **Render** and **Get** put the file into the binary field you named (`data` by default), ready to attach to an email or upload to cloud storage: - The file name is the document's `filename`, and the MIME type its `content_type`. XRechnung and Peppol BIS e-invoice templates produce XML (`application/xml`) rather than PDF. - The file is fetched from the document's short-lived signed URL. Your API key isn't sent with that request. - A document that isn't `rendered` yet (an async render, or one that failed) has no file. The node fails with its status, and with the render error for a failed document. ### Errors [#errors] When the data doesn't match the template's schema, Druckling answers `422` and the node fails with the first wrong field, for example: ```txt Invalid data for field "customer.name": Required field customer.name was missing from the request payload ``` The error details list every invalid field. Turn on **Continue On Fail** to route such items onward with an `error` property instead of stopping the workflow. For `429` responses, use the node's **Retry On Fail** setting; if the code is `quota_exceeded`, your workspace has used its monthly documents. See [Errors](/docs/concepts/errors). ## Druckling Trigger [#druckling-trigger] The trigger starts a workflow for the document events you pick: | Event | Sent when | | --- | --- | | `document.rendered` | A document finished rendering, synchronously or async. | | `document.failed` | Payload validation or rendering failed. | | `document.expired` | A stored file passed its retention period and was deleted. | The API's `batch.completed` event isn't available in the trigger. See [Webhooks](/docs/guides/webhooks) for every event. ### How it subscribes [#how-it-subscribes] - **Activating** the workflow, or **Listen for test event**, creates a webhook endpoint in Druckling for the node's URL and events ([`POST /v1/webhook_endpoints`](/docs/api-reference/webhooks/create)). It shows up in **Developers › Webhooks** as `n8n: `. The endpoint id and its signing secret stay in the workflow's static data. - **Changing the events** replaces the endpoint the next time the workflow is activated. - **Deactivating** the workflow deletes the endpoint again. Each active trigger uses one of the workspace's 20 webhook endpoints. ### Signature verification [#signature-verification] Every delivery is checked with the [Standard Webhooks](https://www.standardwebhooks.com) scheme before the workflow starts: the HMAC-SHA256 of `webhook-id`, `webhook-timestamp` and the raw body must match one of the `v1,…` signatures in `webhook-signature` (there can be several while a secret is rotated), and the timestamp must be within 5 minutes. Anything else gets `401` and starts nothing. Deliveries for events you didn't select, and the dashboard's **Send test event** (`webhook.ping`), are acknowledged without starting the workflow. To try the trigger, render a document with a test key. ### What the workflow receives [#what-the-workflow-receives] One item with the event: ```json { "id": "evt_…", "object": "event", "type": "document.rendered", "created_at": "2026-10-27T10:00:04.000Z", "test_mode": true, "data": { "id": "pdf_WvSdGvCMqjllJNqy", "object": "document", "status": "rendered", "template": "invoice-standard", "filename": "INV-2042.pdf", "pages": 1, "url": "https://…" } } ``` `data` is the document, shortened here; see [Webhooks](/docs/guides/webhooks) for the full payload. To get the file, add **Druckling › Document › Get** with **Download PDF** and the Document ID `{{ $json.data.id }}`. ### Requirements [#requirements] - **A public `https://` URL.** Druckling only delivers to public HTTPS addresses, and the trigger refuses to activate otherwise. A self-hosted n8n must be reachable from the internet over HTTPS with [`WEBHOOK_URL`](https://docs.n8n.io/hosting/configuration/configuration-examples/webhook-url/) set; `http://localhost:5678` won't work, so use a tunnel while developing. - **A full-access key**, to manage the endpoint. - **The key's mode.** A trigger with a test key only receives test-mode events, one with a live key only live events. Every event carries `test_mode`. To go live, deactivate the workflow (which removes its test endpoint), switch the credential to a live key and activate it again. Druckling expects an answer within 10 seconds. The trigger answers as soon as it has verified the delivery, however long the workflow then runs. ## Example: email an invoice for each new spreadsheet row [#example-email-an-invoice-for-each-new-spreadsheet-row] This workflow renders the `invoice-standard` starter for every row added to a Google Sheet and emails it to the customer. The sheet has the columns `invoice_number`, `due_date` (as `2026-11-22`), `customer_name`, `customer_address`, `customer_email`, `description`, `qty` and `rate`. ### Start on new rows [#start-on-new-rows] Add a **Google Sheets Trigger** node that fires on **Row Added** for your sheet. ### Shape the invoice data [#shape-the-invoice-data] Add a **Code** node in **Run Once for Each Item** mode. Spreadsheet cells arrive as text, and the template's schema expects numbers for quantities and amounts, so convert them here: ```js title="Code" const qty = Number($json.qty); const rate = Number($json.rate); const subtotal = qty * rate; const tax = Math.round(subtotal * 8) / 100; return { json: { invoice: { number: $json.invoice_number, due_date: $json.due_date }, customer: { name: $json.customer_name, address: $json.customer_address }, line_items: [{ description: $json.description, qty, rate, amount: subtotal }], totals: { subtotal, tax, amount: subtotal + tax }, }, }; ``` ### Render the invoice [#render-the-invoice] Add a **Druckling** node: - **Resource:** Document. **Operation:** Render. - **Template:** `invoice-standard`. - **Data Mode:** JSON, with **Data** set to the expression `{{ $json }}`. - **Download PDF:** on, into the field `data`. - **Options › Filename:** `{{ $json.invoice.number }}.pdf`. ### Email it [#email-it] Add your email node (Gmail, Microsoft Outlook or Send Email), send it to `{{ $('Google Sheets Trigger').item.json.customer_email }}`, and attach the binary field `data`. Run it once with a test key; the invoices show up in **Documents** in test mode and don't count toward your usage. Then switch the credential to a live key. ## Next steps [#next-steps] How a template's variables turn into the JSON Schema your data must match. Events, retries and signatures behind the trigger. Let an n8n AI Agent build templates and render documents. # PNG output (/docs/guides/png-output) > Render one page of a document as a PNG image for previews, thumbnails and images in emails or messages. Besides PDFs, Druckling can render one page of a document as a PNG image. Use it where a PDF is awkward: a preview in your app, a thumbnail in a list, a ticket or certificate shown inline in an email or a chat message. A PNG render takes the same template, data and language as a PDF render. You add `format: "png"` and, optionally, which page to render and at what resolution. ## Render a page as PNG [#render-a-page-as-png] Send `format: "png"` to [`POST /v1/documents`](/docs/api-reference/documents/create). The `image` object picks the page and the scale: ```bash tab="cURL" curl https://druckling-nine.vercel.app/v1/documents \ -H "Authorization: Bearer $DRUCKLING_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "template": "invoice-standard", "format": "png", "image": { "page": 1, "scale": 1 }, "filename": "INV-2041-preview", "data": { "invoice": { "number": "INV-2041", "due_date": "2026-11-22" }, "customer": { "name": "Northwind Ltd.", "address": "12 Pier St, Leeds" }, "line_items": [ { "description": "Design system audit", "qty": 12, "rate": 180, "amount": 2160 } ], "totals": { "subtotal": 2160, "tax": 172.8, "amount": 2332.8 } } }' ``` ```ts tab="TypeScript" import Druckling from "@druckling/sdk"; const druckling = new Druckling(); // reads DRUCKLING_API_KEY const document = await druckling.documents.create({ template: "invoice-standard", format: "png", filename: "INV-2041-preview", data: { invoice: { number: "INV-2041", due_date: "2026-11-22" }, customer: { name: "Northwind Ltd.", address: "12 Pier St, Leeds" }, line_items: [{ description: "Design system audit", qty: 12, rate: 180, amount: 2160 }], totals: { subtotal: 2160, tax: 172.8, amount: 2332.8 }, }, }); const png = await druckling.documents.download(document); // Uint8Array ``` ```python tab="Python" from druckling import Druckling client = Druckling() # reads DRUCKLING_API_KEY document = client.documents.create( template="invoice-standard", format="png", filename="INV-2041-preview", data={ "invoice": {"number": "INV-2041", "due_date": "2026-11-22"}, "customer": {"name": "Northwind Ltd.", "address": "12 Pier St, Leeds"}, "line_items": [{"description": "Design system audit", "qty": 12, "rate": 180, "amount": 2160}], "totals": {"subtotal": 2160, "tax": 172.8, "amount": 2332.8}, }, ) client.documents.download_to(document, "INV-2041-preview.png") ``` ```php tab="PHP" documents->create( template: 'invoice-standard', format: 'png', filename: 'INV-2041-preview', data: [ 'invoice' => ['number' => 'INV-2041', 'due_date' => '2026-11-22'], 'customer' => ['name' => 'Northwind Ltd.', 'address' => '12 Pier St, Leeds'], 'line_items' => [['description' => 'Design system audit', 'qty' => 12, 'rate' => 180, 'amount' => 2160]], 'totals' => ['subtotal' => 2160, 'tax' => 172.8, 'amount' => 2332.8], ], ); $druckling->documents->downloadTo($document, __DIR__ . '/INV-2041-preview.png'); ``` The SDKs send `format`, but not the `image` options yet. Their PNGs are page 1 at scale 2. For another page or scale, call the REST API directly, as in the cURL example. ## Options [#options] `image` is only allowed together with `format: "png"`. The other parameters (`template`, `version`, `data`, `filename`, `async`, `language`) work exactly as for PDFs. ### Pixel size [#pixel-size] A point is 1/72 inch, so the resolution is 72 × `scale` dpi, and the image is the page size in points × `scale`, rounded to whole pixels: | Page | `scale: 0.5` | `scale: 1` | `scale: 2` (default) | `scale: 4` | | --- | --- | --- | --- | --- | | A4 portrait | 298 × 421 | 595 × 842 | 1191 × 1684 | 2381 × 3368 | | A4 landscape | 421 × 298 | 842 × 595 | 1684 × 1191 | 3368 × 2381 | | A5 portrait | 210 × 298 | 420 × 595 | 839 × 1191 | 1678 × 2381 | | A6 landscape | 210 × 149 | 420 × 298 | 839 × 595 | 1678 × 1191 | | Letter portrait | 306 × 396 | 612 × 792 | 1224 × 1584 | 2448 × 3168 | The image always has the page's proportions, and page sizes are paper and label formats. For a fixed image format such as a 1200 × 630 social card, crop or resize the PNG yourself. The page is drawn on a white background: transparent areas come out white, as in a PDF viewer. ## The response [#the-response] A PNG render returns a [document](/docs/concepts/documents) like a PDF render does, with a few differences: ```json { "id": "pdf_8Qw2kLm3nP0aB1cD", "object": "document", "status": "rendered", "template": "invoice-standard", "version": 1, "filename": "INV-2041-preview.png", "format": "png", "content_type": "image/png", "image": { "page": 1, "scale": 1, "width": 595, "height": 842 }, "pages": 1, "size_bytes": 61204, "url": "https://…", "expires_at": "2026-11-21T10:02:11.000Z", "error": null, "einvoice": null, "batch": null, "language": "en", "test_mode": true, "created_at": "2026-10-22T10:02:10.000Z" } ``` - `format` is `png` and `content_type` is `image/png`. - `image` repeats the page and scale and adds the `width` and `height` in pixels once the image is rendered. For an `async: true` request they're `null` until the document is `rendered`. - `pages` is always 1: the file holds one page, however long the document is. - The file name ends in `.png`. If you pass a `filename` ending in `.pdf`, the extension is replaced. Download the image from `url` like any other document. The signed URL works without an API key, so a browser can also load it directly until it expires; see [Documents](/docs/concepts/documents) for how long URLs and files last. For images in emails, download the PNG and attach or host it yourself, so it keeps working after the URL expires. ## Which templates render PNG [#which-templates-render-png] Any template without e-invoicing can render PNG. E-invoice templates can't: - Factur-X and ZUGFeRD templates render `pdf` only, because the invoice XML has to be embedded in a PDF/A-3. - XRechnung and Peppol BIS templates render `xml` only. Asking them for a PNG answers 422 `validation_failed` on `format`. See [E-invoicing](/docs/guides/e-invoicing). A template's PDF standard (PDF/A or PDF/UA) doesn't apply to images: the PNG is rendered from the same layout without a conformance claim, and the document's timeline in the dashboard notes it. See [Accessible PDFs](/docs/guides/accessible-pdfs). To render page 3, Druckling typesets the whole document and then draws that page, so a PNG takes about as long as the PDF and the same page limit applies. ## Errors [#errors] | Problem | Response | | --- | --- | | `image` without `format: "png"` | 422 `validation_failed`, `field: "image"`: `` `image` options only apply to format "png" `` | | `image.page` past the end of the document | 422 `validation_failed`, `field: "image.page"`: `Page 3 does not exist: the document has 1 page`. `data.pages` holds the page count | | `image.page` below 1 or not a whole number, `image.scale` outside 0.5 to 4 | 400 `BAD_REQUEST`, `Input validation failed`, with the offending path in `data.issues` | | An e-invoice template | 422 `validation_failed`, `field: "format"` | The page count is only known after typesetting, so `image.page` past the end is reported by the render. With `async: true` the request is accepted, and the document ends `failed` with that error (and a `document.failed` [webhook](/docs/guides/webhooks) if you subscribed). If you don't know how long a document will be, render page 1, or render the PDF first and read its `pages`. ## Usage and batches [#usage-and-batches] - In live mode, each rendered PNG counts as one document toward your [plan's quota](/docs/concepts/plans-and-limits), like a PDF. Failed renders don't count, and test-mode renders never do. - [Batches](/docs/guides/batches) render PDFs (or XML for XRechnung and Peppol templates), not PNGs. To make images of many records, send one request per record, with `async: true` and [webhooks](/docs/guides/webhooks) for large volumes. - [Share links](/docs/concepts/share-links) work for PNG documents too. ## Use cases [#use-cases] - **Thumbnails.** Show `scale: 0.5` previews of generated invoices or contracts in your app's lists. - **Previews before sending.** Let a user check page 1 as an image before you send the PDF. - **Images in emails and messages.** Many email clients and chat apps show images inline but PDFs only as attachments. Render a ticket or a certificate as PNG at `scale: 2` for sharp text on high-density screens. - **Every language.** Pass `language` to preview each [translation](/docs/guides/languages) of a template. # Team members and roles (/docs/guides/team) > Invite people to a workspace, choose what each of them can do, and hand over or leave a workspace safely. Everything in Druckling lives in a workspace: templates, documents, batches, API keys, webhook endpoints, embed settings, the plan and its usage. You invite people to a workspace by email, and each member has one of three roles: **Owner**, **Admin** or **Member**. ## Workspaces [#workspaces] One account can belong to several workspaces, for example your company's and a client's. Switch between them with the workspace menu at the top of the sidebar, where **New workspace** also creates another one. New workspaces start with the starter templates, and you're their owner. You can create a workspace as long as you belong to fewer than 10. Workspaces are fully separate. An API key only works in the workspace it was created in, and nothing is shared between workspaces, including the plan and its usage. ## Roles [#roles] | | Owner | Admin | Member | | --- | :---: | :---: | :---: | | Design, publish, duplicate and delete templates | ✓ | ✓ | ✓ | | Render documents, run and cancel batches, create share links | ✓ | ✓ | ✓ | | Use Druck, the AI assistant | ✓ | ✓ | ✓ | | See logs, metrics, usage, the list of API keys, webhook endpoints and their deliveries | ✓ | ✓ | ✓ | | Create and revoke API keys | ✓ | ✓ | | | Add, edit and delete webhook endpoints, reveal and rotate their secrets, send test events and resend deliveries | ✓ | ✓ | | | Manage billing: subscribe, change plan, payment details and invoices | ✓ | ✓ | | | Manage the embedded editor's allowed origins under **Settings › Embed** | ✓ | ✓ | | | Invite people, see pending invitations, resend and revoke them | ✓ | ✓ | | | Change roles between admin and member, remove admins and members | ✓ | ✓ | | | Make someone an owner, change an owner's role, remove an owner | ✓ | | | | Delete the workspace | ✓ | | | A workspace can have several owners, and always keeps at least one. There's no limit on the number of members per plan. Roles apply to people in the dashboard. API keys have their own permissions, **Render only** or **Full access**, whoever created them. See [Authentication](/docs/authentication). ## Invite people [#invite-people] ### Send the invitation [#send-the-invitation] Owners and admins open **Settings › Team** and click **Invite member**. Enter the person's email address, choose **Member** or **Admin**, and click **Send invitation**. You can't invite someone as an owner. Once they've joined, an owner can promote them. ### They get an email [#they-get-an-email] Druckling emails them a link to `/invite/…`. The link works for 7 days, and only for the invited email address. ### Manage pending invitations [#manage-pending-invitations] Invitations that haven't been accepted yet are listed under **Pending invitations**, where the **⋯** menu offers: - **Copy invite link**, to share the link another way, for example if the email didn't arrive. Expired invitations have to be renewed first. - **Resend email** for a pending invitation, or **Renew and resend** for an expired one. Either way the link works for 7 more days. - **Revoke invitation**, which makes the link stop working. Inviting an address that already has a pending invitation renews that invitation, with the role you chose, instead of creating a second one. Inviting an existing member answers with an error. A workspace can have up to 50 pending invitations at a time. Invitation emails to the same address are limited to a few per hour; if you hit the limit, copy the invite link instead. ## Accept an invitation [#accept-an-invitation] The invitation link opens a page that shows the workspace, who invited you, and your role. - **New to Druckling?** Click **Create account** and sign up with the invited email address; it's filled in for you. You land back on the invitation, so you don't have to create a workspace of your own first. - **Already have an account?** Click **Sign in** with the invited address. - **Signed in with another address?** The page offers to sign you out so you can sign in as the invited address. The invitation can't be accepted from a different account. Then click the **Join** button to open the workspace. Email addresses are compared ignoring case. If you're already a member, the page offers **Open workspace** instead. An expired, revoked or already used invitation can't be accepted. Ask an owner or admin of the workspace to invite you again. ## Change roles [#change-roles] Owners and admins change a member's role in the **Role** column of **Settings › Team**. The menu only offers the roles you're allowed to give: - Admins can switch people between admin and member, but can't make anyone an owner or change an owner's role. - Owners can give any role, including owner, and can demote other owners. - The last owner can't be demoted. Make someone else an owner first. Druckling asks you to confirm before you make someone an owner or change your own role. Demoting yourself takes away what your current role allows, and only an owner or admin can give it back. ## Remove members and leave [#remove-members-and-leave] To remove someone, open the **⋯** menu on their row in **Settings › Team** and choose **Remove from workspace**. They lose access right away. Admins can remove admins and members; only owners can remove an owner. To leave a workspace, choose **Leave workspace** in the **⋯** menu on your own row. The last owner can't leave: make someone else an owner first, or delete the workspace. After leaving, you continue in another of your workspaces, or create a new one if you have none. People who left or were removed need a new invitation to come back. ## API keys and departing members [#api-keys-and-departing-members] API keys belong to the workspace, not to the person who created them. They keep working when that person leaves, is removed, or deletes their account. Druckling doesn't record which member created a key, so give keys descriptive names, and when someone with access to them leaves, revoke and replace the keys they could have copied under **Developers › API keys**. The same goes for everything else people create: templates, documents, batches and webhook endpoints stay in the workspace when their creator leaves. ## Delete a workspace or your account [#delete-a-workspace-or-your-account] - **Delete a workspace:** an owner opens **Settings › Workspace**, chooses **Delete workspace** and types the workspace's slug to confirm. This deletes every template, document, file, API key, webhook, log and Druck conversation, and cancels the subscription. API keys stop working immediately. It can't be undone. - **Delete your account:** also under **Settings › Workspace**. It deletes your sign-in and the workspaces where you're the only member. If you're the only owner of a workspace that has other members, make one of them an owner, or remove them, first. ## Who did what [#who-did-what] Druckling doesn't keep a separate audit log of team changes, but these records show who did what: - A template's version history shows when each version was published and the ID of the member who published it. Versions published from the [embedded editor](/docs/guides/embedded-editor) show `embed:` followed by your user's ID. - Documents and batches record the API key that created them, or **Dashboard**. - **Developers › Logs** lists API requests with the key that made each one. - **Pending invitations** shows who sent each invitation. # Webhooks (/docs/guides/webhooks) > Get a signed HTTPS request when documents render, fail or expire and when batches finish, and verify it before you act on it. Webhooks tell your server when something happens to a document or a batch, so you don't have to poll. Druckling sends a signed JSON `POST` to your HTTPS endpoint for each event. Requests follow the [Standard Webhooks](https://www.standardwebhooks.com/) spec, so the official SDKs, the Standard Webhooks libraries or a few lines of your own code can verify them. ## Event types [#event-types] | Event | Sent when | `data` | | --- | --- | --- | | `document.rendered` | A document finished rendering. | The document, with a signed download `url`. | | `document.failed` | A document failed: its payload didn't validate, or rendering failed. | The document, with an `error`. | | `document.expired` | A document's file was deleted after the [retention period](/docs/concepts/documents). | The document, with `status: "expired"` and no `url`. | | `batch.completed` | A [batch](/docs/guides/batches) finished as `completed`, `failed` or `canceled`. Sent once per batch. | The batch, with `counts` and `zip_url`. | | `webhook.ping` | You clicked **Send test event** in the dashboard. You can't subscribe to it. | `{ "object": "ping", "endpoint_id": "whe_…", "message": "…" }` | Documents send these events however they were created: synchronous and asynchronous renders, batch items, and renders from the dashboard. A synchronous request whose payload fails validation answers `422` and also sends `document.failed`. The one exception is batch items that are canceled or never start rendering: they don't send `document.failed`, and the batch's `batch.completed` covers them. ## Add an endpoint [#add-an-endpoint] Endpoints belong to the workspace and to one mode. A test endpoint only receives events from test-mode documents and batches, a live endpoint only live ones. A workspace can have up to 20 endpoints. ### In the dashboard [#in-the-dashboard] Open **Developers › Webhooks** and click **Add endpoint**. Enter the URL, an optional description, the events to send, and the mode (**Test** or **Live**). The signing secret appears once the endpoint is added; you can reveal it again later from the endpoint's page. ### With the API [#with-the-api] [`POST /v1/webhook_endpoints`](/docs/api-reference/webhooks/create) creates an endpoint in the API key's mode. It needs a **Full access** key; a **Render only** key gets `403`. ```bash tab="cURL" curl https://druckling-nine.vercel.app/v1/webhook_endpoints \ -H "Authorization: Bearer $DRUCKLING_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://example.com/webhooks/druckling", "events": ["document.rendered", "document.failed", "batch.completed"], "description": "Invoice mailer" }' ``` ```ts tab="TypeScript" import Druckling from "@druckling/sdk"; const druckling = new Druckling(); const endpoint = await druckling.webhookEndpoints.create({ url: "https://example.com/webhooks/druckling", events: ["document.rendered", "document.failed"], description: "Invoice mailer", }); console.log(endpoint.id, endpoint.secret); ``` ```python tab="Python" from druckling import Druckling client = Druckling() endpoint = client.webhook_endpoints.create( url="https://example.com/webhooks/druckling", events=["document.rendered", "document.failed", "batch.completed"], description="Invoice mailer", ) print(endpoint.id, endpoint.secret) ``` ```php tab="PHP" webhookEndpoints->create( url: 'https://example.com/webhooks/druckling', events: ['document.rendered', 'document.failed', 'batch.completed'], description: 'Invoice mailer', ); echo $endpoint->id, ' ', $endpoint->secret, PHP_EOL; ``` The answer is `201` with the endpoint and its `secret` (`whsec_…`). The API returns the secret only in this response, so store it now, for example as `DRUCKLING_WEBHOOK_SECRET`. The SDKs' event types only list the `document.*` events so far. In TypeScript, `"batch.completed"` in `events` is a type error, so subscribe to it with cURL or in the dashboard; the Python and PHP SDKs pass it through as is. All three SDKs verify `batch.completed` deliveries like any other event; see [Handle batch events](#handle-batch-events). [`GET /v1/webhook_endpoints`](/docs/api-reference/webhooks/list) and [`GET /v1/webhook_endpoints/{id}`](/docs/api-reference/webhooks/get) list and fetch the endpoints of the key's mode, and [`DELETE /v1/webhook_endpoints/{id}`](/docs/api-reference/webhooks/delete) removes one. Everything else happens in the dashboard: editing the URL, events and description, turning an endpoint off and on, revealing and rotating the secret, sending test events and resending deliveries. An endpoint's mode can't change; add a new endpoint for the other mode. In the dashboard, only owners and admins can add, change or delete endpoints, see secrets, and send or resend events. Members can see endpoints and their deliveries. See [Team members and roles](/docs/guides/team). ### URL requirements [#url-requirements] - The URL must start with `https://` and be at most 2,048 characters. - The host must be reachable on the public internet. `localhost`, private and link-local IP addresses, hosts without a dot, and hosts ending in `.local`, `.internal` or `.localhost` are rejected. Before every delivery, Druckling checks again that the host resolves to a public address. - Redirects aren't followed. A `3xx` answer counts as a failed delivery. - Any `#fragment` is dropped. To receive webhooks on your laptop, expose your local server through an HTTPS tunnel and register the tunnel's public URL as a test endpoint. ## What Druckling sends [#what-druckling-sends] Each delivery is a `POST` with a JSON body and these headers: | Header | Value | | --- | --- | | `content-type` | `application/json` | | `user-agent` | `Druckling-Webhooks/1.0` | | `webhook-id` | The event ID, e.g. `evt_7Lq2Vb9XmR4tKp8N`. The same for every attempt and every resend of the event. | | `webhook-timestamp` | Unix time in seconds when this attempt was sent. | | `webhook-signature` | `v1,` followed by the base64 signature. Several space-separated signatures while a secret is being [rotated](#rotate-the-signing-secret). | The body is an event envelope: | Field | Description | | --- | --- | | `id` | Event ID, the same as the `webhook-id` header. | | `object` | Always `"event"`. | | `type` | The event type, e.g. `document.rendered`. | | `created_at` | When the event happened (ISO 8601). Retries keep this value. | | `test_mode` | `true` for test-mode events. | | `data` | The [document](/docs/api-reference/documents/get) or [batch](/docs/api-reference/batches/get), exactly as the API returns it. | `data` is a snapshot taken when the event happens. Retries and resends deliver the same body. ```json { "id": "evt_7Lq2Vb9XmR4tKp8N", "object": "event", "type": "document.rendered", "created_at": "2026-10-27T09:41:07.498Z", "test_mode": false, "data": { "id": "pdf_8Qw2kLm3nP0aB1cD", "object": "document", "status": "rendered", "template": "invoice-standard", "version": 3, "filename": "INV-2041.pdf", "format": "pdf", "content_type": "application/pdf", "image": null, "pages": 1, "size_bytes": 36033, "url": "https://files.example.com/pdf_8Qw2kLm3nP0aB1cD.pdf?signature=…", "expires_at": "2026-11-26T09:41:07.498Z", "error": null, "einvoice": null, "batch": null, "language": "en", "test_mode": false, "created_at": "2026-10-27T09:41:06.210Z" } } ``` ```json { "id": "evt_3Fm8QzT1vK6nRw2Y", "object": "event", "type": "document.failed", "created_at": "2026-10-27T09:44:19.031Z", "test_mode": false, "data": { "id": "pdf_2Vn7RtY4kQ9mXc1B", "object": "document", "status": "failed", "template": "invoice-standard", "version": 3, "filename": "INV-2042.pdf", "format": "pdf", "content_type": "application/pdf", "image": null, "pages": null, "size_bytes": null, "url": null, "expires_at": null, "error": { "code": "schema_validation_failed", "message": "Required field customer.address was missing from the request payload", "field": "customer.address" }, "einvoice": null, "batch": null, "language": "en", "test_mode": false, "created_at": "2026-10-27T09:44:19.012Z" } } ``` ```json { "id": "evt_9Kc4WpN2xL7tQm5R", "object": "event", "type": "document.expired", "created_at": "2026-11-27T03:17:12.640Z", "test_mode": false, "data": { "id": "pdf_8Qw2kLm3nP0aB1cD", "object": "document", "status": "expired", "template": "invoice-standard", "version": 3, "filename": "INV-2041.pdf", "format": "pdf", "content_type": "application/pdf", "image": null, "pages": 1, "size_bytes": 36033, "url": null, "expires_at": "2026-11-26T09:41:07.498Z", "error": null, "einvoice": null, "batch": null, "language": "en", "test_mode": false, "created_at": "2026-10-27T09:41:06.210Z" } } ``` ```json { "id": "evt_5Rn2XqK8wT1mZp4L", "object": "event", "type": "batch.completed", "created_at": "2026-10-27T09:52:41.902Z", "test_mode": false, "data": { "id": "bat_3Hk9QmZ1xT7pLw2V", "object": "batch", "status": "completed", "template": "invoice-standard", "version": 3, "filename_pattern": "invoice-{{invoice.number}}.pdf", "counts": { "total": 250, "pending": 0, "rendered": 248, "failed": 2, "canceled": 0 }, "zip_url": "https://files.example.com/bat_3Hk9QmZ1xT7pLw2V.zip?signature=…", "zip_size_bytes": 9035112, "zip_expires_at": "2026-11-26T09:52:41.902Z", "error": null, "test_mode": false, "created_at": "2026-10-27T09:48:02.114Z", "finished_at": "2026-10-27T09:52:41.902Z" } } ``` ```json { "id": "evt_2Zt8LqW4mN7xKp3V", "object": "event", "type": "webhook.ping", "created_at": "2026-10-27T09:30:00.000Z", "test_mode": true, "data": { "object": "ping", "endpoint_id": "whe_4Fq9LmZ2xR8tKpWc", "message": "Test event from Druckling. Verify the signature, then answer with any 2xx status." } } ``` A `document.*` event for a batch item has `data.batch` set to `{ "id": "bat_…", "index": 12 }`, the item's position in the batch. ## Verify signatures [#verify-signatures] Anyone who knows your endpoint's URL can send it requests, so check every request's signature before you trust it. Druckling signs each attempt like this: 1. Take the part of the secret after `whsec_` and base64-decode it. That's the HMAC key. 2. Build the signed content: `{webhook-id}.{webhook-timestamp}.{body}`, with the **raw** request body exactly as received. 3. Compute HMAC-SHA256 over it and base64-encode the result. 4. Send it in `webhook-signature` as `v1,`. To verify, recompute the signature and compare it in constant time with each `v1,` entry of the header; one match is enough. Also reject requests whose `webhook-timestamp` is more than 5 minutes from your clock, which stops old requests from being replayed. That's the tolerance the SDKs use by default. Verify the body bytes exactly as they arrived. Parsing the JSON and serializing it again changes whitespace or key order and breaks the signature. In Express, use `express.raw()` on the webhook route; in Next.js, read `await request.text()`; in Flask, `request.get_data()`; in PHP, `file_get_contents('php://input')`. ### With an SDK [#with-an-sdk] Each SDK has a verify helper that checks the signature and the timestamp and returns the parsed event, or throws when anything is off. See [SDKs](/docs/sdks) to install one. | SDK | Function | Throws | | --- | --- | --- | | TypeScript | `verifyWebhook(rawBody, headers, secret, { toleranceSeconds? })` | `WebhookVerificationError` | | Python | `verify_webhook(raw_body, headers, secret, *, tolerance=300)` | `WebhookVerificationError` | | PHP | `Webhook::verify($rawBody, $headers, $secret, $tolerance = 300)` | `WebhookVerificationException` | ```ts tab="Next.js" title="app/api/webhooks/druckling/route.ts" import { verifyWebhook, WebhookVerificationError } from "@druckling/sdk"; export async function POST(request: Request) { let event; try { event = await verifyWebhook(await request.text(), request.headers, process.env.DRUCKLING_WEBHOOK_SECRET!); } catch (error) { if (error instanceof WebhookVerificationError) return new Response("Invalid signature", { status: 400 }); throw error; } if (event.type === "document.rendered") { await enqueueInvoiceEmail(event.id, event.data.id); } else if (event.type === "document.failed") { await notifyTeam(event.id, event.data.id, event.data.error?.message); } return new Response(null, { status: 204 }); } ``` ```ts tab="Express" title="server.ts" import express from "express"; import { verifyWebhook, WebhookVerificationError } from "@druckling/sdk"; const app = express(); app.post("/webhooks/druckling", express.raw({ type: "application/json" }), async (req, res, next) => { try { const event = await verifyWebhook(req.body, req.headers, process.env.DRUCKLING_WEBHOOK_SECRET!); if (event.type === "document.rendered") await enqueueInvoiceEmail(event.id, event.data.id); res.sendStatus(204); } catch (error) { if (error instanceof WebhookVerificationError) return res.sendStatus(400); next(error); } }); ``` ```python tab="Flask" title="app.py" import os from flask import Flask, request from druckling import WebhookVerificationError, verify_webhook app = Flask(__name__) SECRET = os.environ["DRUCKLING_WEBHOOK_SECRET"] @app.post("/webhooks/druckling") def druckling_webhook(): try: event = verify_webhook(request.get_data(), request.headers, SECRET) except WebhookVerificationError: return "Invalid signature", 400 if event.type == "document.rendered": enqueue_invoice_email(event.id, event.document.id) elif event.type == "document.failed": notify_team(event.id, event.document.id, event.document.error.message) return "", 204 ``` ```python tab="FastAPI" title="main.py" import os from fastapi import FastAPI, HTTPException, Request, Response from druckling import WebhookVerificationError, verify_webhook app = FastAPI() SECRET = os.environ["DRUCKLING_WEBHOOK_SECRET"] @app.post("/webhooks/druckling") async def druckling_webhook(request: Request) -> Response: try: event = verify_webhook(await request.body(), request.headers, SECRET) except WebhookVerificationError: raise HTTPException(status_code=400, detail="Invalid signature") if event.type == "document.rendered": await enqueue_invoice_email(event.id, event.document.id) return Response(status_code=204) ``` ```php tab="PHP" title="webhook.php" type === WebhookEvent::DOCUMENT_RENDERED) { enqueueInvoiceEmail($event->id, $event->document->id); } elseif ($event->type === WebhookEvent::DOCUMENT_FAILED) { notifyTeam($event->id, $event->document->id, $event->document->error?->message); } http_response_code(204); ``` `enqueueInvoiceEmail` and `notifyTeam` stand for your own code. Pass the event ID along so the work can be [deduplicated](#duplicates-and-ordering). The event object mirrors the envelope. In TypeScript, `event.data` is the document. In Python and PHP, `event.document` (`$event->document`) is the parsed document for `document.*` events and `None` (`null`) otherwise, while `event.data` (`$event->data`) is always the raw `data` object. In PHP, `$_SERVER` works as the headers array too. ### Handle batch events [#handle-batch-events] `batch.completed` verifies like any other event, but the SDKs don't have a type for it yet, so read the batch from the raw `data`: ```ts tab="TypeScript" interface BatchData { id: string; status: "completed" | "failed" | "canceled"; counts: { total: number; rendered: number; failed: number; canceled: number }; zip_url: string | null; } if ((event.type as string) === "batch.completed") { const batch = event.data as unknown as BatchData; if (batch.status === "completed") await enqueueZipDownload(event.id, batch.id); } ``` ```python tab="Python" if event.type == "batch.completed": batch = event.data if batch["status"] == "completed": enqueue_zip_download(event.id, batch["id"]) ``` ```php tab="PHP" if ($event->type === 'batch.completed' && $event->data['status'] === 'completed') { enqueueZipDownload($event->id, $event->data['id']); } ``` The SDKs' document types also don't include `batch` yet. Read `event.data.batch` through a cast in TypeScript, or from `event.data["batch"]` and `$event->data['batch']` in Python and PHP. ### By hand [#by-hand] Without an SDK, verification takes a few lines of standard library code. Each example takes the raw body, the three `webhook-*` headers and the `whsec_…` secret, and returns the parsed event. ```js tab="Node.js" title="verify-webhook.mjs" import crypto from "node:crypto"; const TOLERANCE_SECONDS = 5 * 60; export function verifyRerenderWebhook(rawBody, headers, secret) { const id = headers["webhook-id"]; const timestamp = headers["webhook-timestamp"]; const signatures = headers["webhook-signature"]; if (!id || !timestamp || !signatures) throw new Error("Missing webhook headers"); if (!/^\d+$/.test(timestamp) || Math.abs(Date.now() / 1000 - Number(timestamp)) > TOLERANCE_SECONDS) { throw new Error("Timestamp outside the tolerance"); } const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64"); const expected = crypto.createHmac("sha256", key).update(`${id}.${timestamp}.`).update(rawBody).digest(); const valid = signatures.split(" ").some((entry) => { const [version, signature] = entry.split(","); if (version !== "v1" || !signature) return false; const given = Buffer.from(signature, "base64"); return given.length === expected.length && crypto.timingSafeEqual(given, expected); }); if (!valid) throw new Error("No matching signature"); return JSON.parse(rawBody); } ``` ```python tab="Python" title="verify_webhook.py" import base64 import hashlib import hmac import json import time TOLERANCE_SECONDS = 5 * 60 def verify_druckling_webhook(raw_body: bytes, headers, secret: str) -> dict: msg_id = headers.get("webhook-id") timestamp = headers.get("webhook-timestamp") signatures = headers.get("webhook-signature") if not msg_id or not timestamp or not signatures: raise ValueError("Missing webhook headers") if not timestamp.isdigit() or abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS: raise ValueError("Timestamp outside the tolerance") key = base64.b64decode(secret.removeprefix("whsec_")) signed = f"{msg_id}.{timestamp}.".encode() + raw_body expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode() for entry in signatures.split(" "): version, _, signature = entry.partition(",") if version == "v1" and hmac.compare_digest(signature, expected): return json.loads(raw_body) raise ValueError("No matching signature") ``` ```php tab="PHP" title="verify-webhook.php" 300) { throw new RuntimeException('Timestamp outside the tolerance'); } $key = base64_decode(preg_replace('/^whsec_/', '', $secret), true); $expected = base64_encode(hash_hmac('sha256', $id . '.' . $timestamp . '.' . $rawBody, $key, true)); foreach (explode(' ', $signatures) as $entry) { [$version, $signature] = array_pad(explode(',', $entry, 2), 2, ''); if ($version === 'v1' && hash_equals($expected, $signature)) { return json_decode($rawBody, true, 512, JSON_THROW_ON_ERROR); } } throw new RuntimeException('No matching signature'); } $event = verifyRerenderWebhook( file_get_contents('php://input'), $_SERVER['HTTP_WEBHOOK_ID'] ?? '', $_SERVER['HTTP_WEBHOOK_TIMESTAMP'] ?? '', $_SERVER['HTTP_WEBHOOK_SIGNATURE'] ?? '', (string) getenv('DRUCKLING_WEBHOOK_SECRET'), ); ``` The Node.js version expects lowercase header names, as in Node's `req.headers`, and a body that is a string or a `Buffer`. The Python version expects a case-insensitive mapping such as Flask's `request.headers`. Python 3.9 or later is needed for `removeprefix`. Check your implementation against this signed request. With the clock set to the timestamp, it must verify, and changing a single byte of the body must make it fail: ```text secret: whsec_MfKQ9r8GKYqrTFLSBT3AmRGeT8ksXcRnjbJ0K9oQBXg= webhook-id: evt_2Zt8LqW4mN7xKp3V webhook-timestamp: 1793093400 webhook-signature: v1,UiRQtira4saHgvPj2tLXnRoUorJPqmF9nQz18r+tObg= body: {"id":"evt_2Zt8LqW4mN7xKp3V","object":"event","type":"webhook.ping","created_at":"2026-10-27T09:30:00.000Z","test_mode":true,"data":{"object":"ping","endpoint_id":"whe_4Fq9LmZ2xR8tKpWc","message":"Test event from Druckling. Verify the signature, then answer with any 2xx status."}} ``` The SDKs can also produce signatures for your own tests: `signWebhook(secret, id, timestamp, body)` in TypeScript, `sign_webhook(secret, msg_id, timestamp, body)` in Python, and `Webhook::sign($secret, $msgId, $timestamp, $body)` in PHP. ## Responses and retries [#responses-and-retries] A delivery succeeds when your endpoint answers with any `2xx` status within 10 seconds. Druckling doesn't interpret the response body; it only keeps the start of it for the [delivery log](#delivery-logs-and-resending). Anything else counts as a failure and is retried: another status code, including `3xx` redirects; no answer within 10 seconds; or a connection or TLS error. Druckling makes up to 7 attempts over about 8.6 hours: | Attempt | Sent | | --- | --- | | 1 | Right away | | 2 | 10 seconds after attempt 1 | | 3 | 1 minute after attempt 2 | | 4 | 5 minutes after attempt 3 | | 5 | 30 minutes after attempt 4 | | 6 | 2 hours after attempt 5 | | 7 | 6 hours after attempt 6 | If attempt 7 fails too, the delivery is marked failed. You can still [resend](#delivery-logs-and-resending) it from the dashboard. Each attempt is signed afresh with a new `webhook-timestamp`; the `webhook-id` and the body stay the same. - **`410 Gone`** stops retries for that delivery right away and turns the endpoint off. Answer `410` only when you want Druckling to stop sending. - **Turning an endpoint off** cancels its pending retries. Events that happen while it's off aren't delivered later, not even after you turn it back on. - **Deleting an endpoint** stops its pending deliveries and removes its delivery history. Druckling doesn't turn endpoints off after other failures, so a broken endpoint keeps receiving attempts. Keep an eye on **Last 7 days** in the endpoint list. ### Duplicates and ordering [#duplicates-and-ordering] - **Duplicates.** The same event can reach you more than once, for example after a timeout on your side or a manual resend. Store the `webhook-id` of the events you've processed and skip repeats. - **Ordering.** Events can arrive in any order. A batch's `batch.completed` can arrive before some of its items' `document.rendered`. Decide what to do from `data.status`, not from the order of arrival. ## Delivery logs and resending [#delivery-logs-and-resending] Open an endpoint under **Developers › Webhooks** to see its recent deliveries, all or only failed ones. Each delivery shows the event type, its status (pending, succeeded or failed), the number of attempts, when the next retry is due, the request body that was sent, and your endpoint's response status and the start of its body (up to 2,000 characters). The endpoint list shows each endpoint's successful and failed deliveries over the last 7 days. Delivery history is kept for 30 days. - **Resend** sends a delivery's event again right away, with the same `webhook-id` and body, so your deduplication recognizes it. It's a single attempt: if it fails, it isn't retried. The endpoint must be turned on. - **Send test event** delivers a `webhook.ping` event once, with no retries, whatever events the endpoint subscribes to. Use it to check your URL and your signature code. Only owners and admins can resend and send test events. ## Rotate the signing secret [#rotate-the-signing-secret] Rotate a secret when it may have leaked, or as routine hygiene. On the endpoint's page under **Developers › Webhooks**, open the **⋯** menu and choose **Rotate signing secret**. The new secret is shown right away. For the next 24 hours, every request is signed with both secrets, so `webhook-signature` carries two entries: ```text webhook-signature: v1, v1, ``` Verification passes as long as one of them matches, which the SDK helpers and the examples above already handle. Deploy the new secret to your server within those 24 hours; after that, only the new secret signs. Rotation is only available in the dashboard. With the API alone, create a second endpoint for the same URL, make your server accept both endpoints' secrets, then delete the old endpoint. While both exist, each event arrives twice with the same `webhook-id`, so your [deduplication](#duplicates-and-ordering) drops the copy. ## Best practices [#best-practices] - **Verify first, then answer quickly.** Check the signature, store or queue the event, and return `2xx` right away. Do slow work, such as sending emails or downloading files, in the background, well within the 10-second limit. - **Deduplicate on `webhook-id`.** Make your processing idempotent so a repeated event does no harm. - **Fetch fresh data before you act on it.** The `url` in a `document.rendered` event was signed when the event happened and works for up to 7 days, and resends deliver the same body. Before downloading, fetch the document again with [`GET /v1/documents/{id}`](/docs/api-reference/documents/get) for a fresh link; do the same for a batch's `zip_url` with [`GET /v1/batches/{id}`](/docs/api-reference/batches/get). - **Keep test and live apart.** Use separate endpoints and secrets for each mode, and check `test_mode` before triggering anything with real-world effects. - **Reconcile now and then.** If missing an event would be costly, also check periodically through the API, for example by [listing documents](/docs/api-reference/documents/list) with `status=failed`. # Introduction (/docs) > Druckling turns templates you design visually and your JSON data into PDFs, e-invoices and images through a REST API hosted in the EU. Druckling is a document generation API. You design a template in a visual editor, bind its text to variables such as `{{customer.name}}`, publish it, and then send JSON data to the API to get the finished PDF back. Pages are typeset by the [Typst](https://typst.app) engine, not printed from a headless browser. It's built for teams that generate documents from application data: invoices, certificates, tickets, reports, contracts and packing slips. Developers integrate the API once; designers and operations teams change templates in the dashboard without a deploy. ## What you can do [#what-you-can-do] - **Design templates visually.** Lay out blocks, fonts and brand colors in the editor, with Druck, the AI assistant, whose changes only apply once you accept them. See [Templates](/docs/concepts/templates). - **Bind your data.** Declare variables and Druckling derives a JSON Schema that every request is validated against. See [Variables](/docs/concepts/variables) and [Template strings](/docs/concepts/template-strings). - **Render documents** as PDF, as a PNG of one page, or as e-invoice XML, while the request waits or in the background. See [Documents](/docs/concepts/documents) and [PNG output](/docs/guides/png-output). - **Create e-invoices**: Factur-X / ZUGFeRD (a PDF/A-3 with the XML embedded), XRechnung 3.0 and Peppol BIS Billing 3.0, checked against the EN 16931 business rules. See [E-invoicing](/docs/guides/e-invoicing). - **Produce accessible PDFs** that conform to PDF/UA-1. See [Accessible PDFs](/docs/guides/accessible-pdfs). - **Render in bulk**: up to 1,000 documents per batch, collected in one ZIP. See [Batches](/docs/guides/batches). - **Render in several languages** from one template. See [Languages](/docs/guides/languages). - **Share documents** through public links that expire. See [Share links](/docs/concepts/share-links). - **Get notified** with signed webhooks when documents render, fail or expire and when batches finish. See [Webhooks](/docs/guides/webhooks). - **Embed the editor** in your own product, white-labeled, so your users can edit their templates. See [Embedded editor](/docs/guides/embedded-editor). - **Connect AI tools and automations** through the hosted [MCP server](/docs/guides/mcp) and the [n8n node](/docs/guides/n8n). - **Use an SDK** for TypeScript, Python or PHP. See [SDKs](/docs/sdks). - **Develop for free** with test keys, whose data stays apart from live data. See [Test mode](/docs/concepts/test-mode). - **Work as a team** with owner, admin and member roles. See [Team](/docs/guides/team). ## How it works [#how-it-works] ### Design a template [#design-a-template] Start from one of the starter templates or a blank page. Add text, tables, images, QR codes and other blocks, and bind them to variables. The variables you declare become the template's data contract. ### Publish a version [#publish-a-version] Publishing freezes the template into an immutable, numbered version. The API only renders published versions, so you can keep editing the draft without changing what your integration produces. Requests use the latest version unless they pin one. ### Render with your data [#render-with-your-data] Send the template's slug and your data to [`POST /v1/documents`](/docs/api-reference/documents/create). Druckling validates the data against the template's schema, renders the document and returns it with a signed download link. ```bash curl https://druckling-nine.vercel.app/v1/documents \ -H "Authorization: Bearer $DRUCKLING_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "template": "invoice-standard", "data": { "invoice": { "number": "INV-2041", "due_date": "2026-11-22" }, "customer": { "name": "Northwind Ltd.", "address": "12 Pier St, Leeds" }, "line_items": [{ "description": "Design system audit", "qty": 12, "rate": 180, "amount": 2160 }], "totals": { "subtotal": 2160, "tax": 172.8, "amount": 2332.8 } } }' ``` The [Quickstart](/docs/quickstart) walks through this request step by step. ## Where your data lives [#where-your-data-lives] Druckling runs in the EU, in Frankfurt, Germany: - The application, the API, file storage and background queues run on Vercel in the `fra1` region. - The database is managed PostgreSQL by Neon in AWS `eu-central-1`. - Rendered files are private. They're reachable only through signed links, which work for at most 7 days, and through share links you create. Files are deleted 30 days after rendering. - The request bodies you send are removed after 30 days. Document records (status, file name, page count, timeline) are kept for a year, and API request logs for 90 days. Druck, the AI assistant in the editor, sends data to a model only when you use it. Its requests are restricted to EU data centers, with zero data retention and no training on your data. A request that no EU data center can serve fails instead of running elsewhere. This applies to Druck: when you connect your own AI tool through the [MCP server](/docs/guides/mcp), that tool's model provider handles what it sends and receives. The [security page](/legal/security) and the [subprocessor list](/legal/subprocessors) have the details. ## Next steps [#next-steps] Create an API key and render your first PDF in a few minutes. Templates, variables, documents, test mode, limits and errors. E-invoicing, batches, languages, webhooks, the embedded editor and more. Typed clients for TypeScript, Python and PHP. Every endpoint, parameter and response field. ## Docs for AI tools [#docs-for-ai-tools] These docs are also available in formats that AI assistants and coding agents read well: - [`/llms.txt`](/llms.txt) is an index of every page. - [`/llms-full.txt`](/llms-full.txt) contains all pages in one file. - Append `.md` to any docs URL to get the page as Markdown, for example [`/docs/quickstart.md`](/docs/quickstart.md). Each page also has actions to copy it as Markdown or open it in ChatGPT or Claude. To let an AI assistant work in your workspace, for example to render documents or edit templates, connect it to Druckling's hosted [MCP server](/docs/guides/mcp). # Quickstart (/docs/quickstart) > Create an account and a test API key, then render your first PDF from the invoice-standard template with cURL or an SDK. This guide takes you from a new account to a rendered PDF. You'll use a test API key, so nothing you render counts toward your plan's quota. ### Create an account [#create-an-account] Sign up at [druckling-nine.vercel.app/sign-up](https://druckling-nine.vercel.app/sign-up) with your name, work email and a password of at least 8 characters. Then name your workspace. A workspace holds your templates, documents, API keys and team. New workspaces start on the Free plan with six starter templates: Invoice (`invoice-standard`), Course certificate, Quarterly report, Event ticket, Rental agreement and Packing slip. `invoice-standard` is already published, so you can render it right away. The other starters are drafts. ### Create a test API key [#create-a-test-api-key] In the dashboard, go to **Developers › API keys** and click **Create API key**: 1. Name the key after what uses it, for example `quickstart`. 2. Keep **Test** as the mode and **Render only** as the permission. 3. Click **Create key** and copy the key. It's shown only once. Store it in an environment variable. The SDKs read `DRUCKLING_API_KEY` by default: ```bash export DRUCKLING_API_KEY="dr_test_…" ``` Test keys render real documents for free and keep their data apart from live data; see [Test mode](/docs/concepts/test-mode). Only owners and admins can create keys, and you're the owner of the workspace you created. See [Authentication](/docs/authentication) for permissions, rotation and revocation. ### Check that the template is published [#check-that-the-template-is-published] The API only renders published versions. Publishing freezes the template's draft into an immutable version (v1, v2, …), so editing a template never changes what your integration produces until you publish again. `invoice-standard` is published as v1, so there's nothing to do for this guide. To render another template, open it under **Templates**, open the editor and click **Publish**, then **Publish v1**. Publishing checks that the template has no errors, that its sample data matches its variables and that it renders. Rendering a template that was never published fails with `404 Not Found`: ```json { "defined": false, "code": "NOT_FOUND", "status": 404, "message": "Template quarterly-report has no published version yet; publish it first", "data": { "code": "not_found", "field": "template" } } ``` ### Render your first PDF [#render-your-first-pdf] Send the template slug and your data to [`POST /v1/documents`](/docs/api-reference/documents/create). The request waits while the PDF renders and returns the finished document. To use an SDK, install it first: The SDKs aren't on npm, PyPI or Packagist yet. Until they are, install them from the Druckling source repository. ```bash tab="TypeScript" git clone https://github.com/vulpery/druckling.git cd druckling/src/integrations/sdk-typescript npm install && npm run build && npm pack # then, in your project npm install /path/to/druckling-sdk-0.1.0.tgz ``` ```bash tab="Python" pip install "git+https://github.com/vulpery/druckling.git#subdirectory=src/integrations/sdk-python" ``` ```bash tab="PHP" git clone https://github.com/vulpery/druckling.git # then, in your project composer config repositories.druckling path /path/to/druckling/src/integrations/sdk-php composer require druckling/druckling-php:@dev ``` Then render the invoice: ```bash tab="cURL" curl https://druckling-nine.vercel.app/v1/documents \ -H "Authorization: Bearer $DRUCKLING_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "template": "invoice-standard", "filename": "INV-2041.pdf", "data": { "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" } } }' ``` ```ts tab="TypeScript" import { writeFile } from "node:fs/promises"; import Druckling from "@druckling/sdk"; const druckling = new Druckling(); // reads DRUCKLING_API_KEY const document = await druckling.documents.create({ template: "invoice-standard", filename: "INV-2041.pdf", data: { 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" }, }, }); console.log(document.status, document.url); await writeFile("INV-2041.pdf", await druckling.documents.download(document)); ``` ```python tab="Python" from druckling import Druckling client = Druckling() # reads DRUCKLING_API_KEY document = client.documents.create( template="invoice-standard", filename="INV-2041.pdf", data={ "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"}, }, ) print(document.status, document.url) client.documents.download_to(document, "INV-2041.pdf") ``` ```php tab="PHP" documents->create( template: 'invoice-standard', data: [ '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'], ], filename: 'INV-2041.pdf', ); echo $document->status, ' ', $document->url, PHP_EOL; $druckling->documents->downloadTo($document, __DIR__ . '/INV-2041.pdf'); ``` The template prints the values you send; it doesn't calculate totals. Each template's **API** tab in the dashboard shows this request with the template's own sample data. ### Handle the response [#handle-the-response] A successful render returns `200 OK` with the [document](/docs/api-reference/documents/get): ```json { "id": "pdf_8Qw2kLm3nP0aB1cD", "object": "document", "status": "rendered", "template": "invoice-standard", "version": 1, "filename": "INV-2041.pdf", "format": "pdf", "content_type": "application/pdf", "image": null, "pages": 1, "size_bytes": 41873, "url": "https://…", "expires_at": "2026-11-26T09:41:07.312Z", "error": null, "einvoice": null, "batch": null, "language": "en", "test_mode": true, "created_at": "2026-10-27T09:41:06.208Z" } ``` - `status` is `rendered`: the file is ready. - `url` is a signed link to the PDF. It needs no API key and works for up to 7 days. Download the file right away, or retrieve the document again with [`GET /v1/documents/{id}`](/docs/api-reference/documents/get) for a fresh link. - `expires_at` is when Druckling deletes the file: 30 days after rendering. After that the document's status becomes `expired` and it has no `url`. - `version` is the template version that was rendered, and `test_mode` tells you which mode the key used. With cURL, download the file from `url`: ```bash curl -o INV-2041.pdf "https://…" ``` For large documents, send `"async": true`. The response then comes back right away with `202 Accepted`, `status: "queued"` and no `url` yet. Poll the document or wait for a [webhook](/docs/guides/webhooks); see [Documents](/docs/concepts/documents). #### When the data doesn't match [#when-the-data-doesnt-match] Druckling validates `data` against the template's JSON Schema before rendering. If you leave out `invoice.number`, the request fails with `422 Unprocessable Content`: ```json { "defined": false, "code": "UNPROCESSABLE_CONTENT", "status": 422, "message": "Required field invoice.number was missing from the request payload", "data": { "code": "schema_validation_failed", "field": "invoice.number", "documentId": "pdf_3Hk9QmZ1xT7pLw2V", "errors": [ { "field": "invoice.number", "message": "missing required field invoice.number" } ] } } ``` - `data.code` is the machine-readable error code. Schema mismatches are `schema_validation_failed`; other invalid input, such as a language the template doesn't have, is `validation_failed`. - `data.field` is the dotted path of the first offending field, for example `line_items.1.qty`. `data.errors` lists every problem found, missing fields first. - The failed attempt is recorded as a `failed` document (`data.documentId`), so you can inspect it under **Documents** in the dashboard. Failed renders don't count toward your quota. The SDKs raise this as a validation error with the same details. Here `payload` stands for the data you send: ```ts tab="TypeScript" import Druckling, { ValidationError } from "@druckling/sdk"; const druckling = new Druckling(); try { await druckling.documents.create({ template: "invoice-standard", data: payload }); } catch (error) { if (!(error instanceof ValidationError)) throw error; for (const problem of error.errors) console.error(`${problem.field}: ${problem.message}`); } ``` ```python tab="Python" from druckling import Druckling, ValidationError client = Druckling() try: client.documents.create(template="invoice-standard", data=payload) except ValidationError as error: for problem in error.errors: print(f"{problem.field}: {problem.message}") ``` ```php tab="PHP" use Druckling\Exception\ValidationException; use Druckling\Druckling; $druckling = new Druckling(); try { $druckling->documents->create(template: 'invoice-standard', data: $payload); } catch (ValidationException $e) { foreach ($e->errors as $problem) { echo "{$problem->field}: {$problem->message}", PHP_EOL; } } ``` See [Errors](/docs/concepts/errors) for every error code. ## Next steps [#next-steps] Learn how a template's variables become the JSON Schema your data must match. Formats, async rendering, polling, retention and signed links. Get notified when documents render or fail instead of polling. What changes when you switch from a test key to a live key. Retries, pagination, downloads and webhook verification in TypeScript, Python and PHP. Every endpoint and field. # SDKs (/docs/sdks) > Official Druckling client libraries for TypeScript, Python and PHP, what they cover and how they behave. Druckling has official SDKs for TypeScript/JavaScript, Python and PHP. They wrap the [REST API](/docs/api-reference) with typed models and errors, and add the parts you would otherwise write yourself: retries with backoff, auto-paging, waiting for async renders, downloading files, and verifying webhook signatures. ## Choose an SDK [#choose-an-sdk] | | TypeScript | Python | PHP | | --- | --- | --- | --- | | Package | `@druckling/sdk` | `druckling` | `druckling/druckling-php` | | Runtime | Node.js 20+, Bun, Deno, Cloudflare Workers, Vercel Functions | Python 3.9+ | PHP 8.1+ with `ext-curl` and `ext-json` | | HTTP layer | `fetch` (the runtime's, or one you pass in) | [`httpx`](https://www.python-httpx.org/) | Built-in curl transport, or any PSR-18 client | | Runtime dependencies | None | `httpx` (`>=0.23,<1`) | None | | Clients | Promise-based | Sync `Druckling` and async `AsyncDruckling` | Synchronous | | Packaging | ESM and CommonJS, bundled type declarations | Typed (`py.typed`), dataclass models | Composer, PSR-4, readonly typed models | | Response fields | snake_case, exactly as in the API | snake_case attributes, `datetime` values | camelCase properties, `DateTimeImmutable` values | `@druckling/sdk` for Node.js, Bun, Deno and edge runtimes. `druckling` with sync and async clients on httpx. `druckling/druckling-php` with curl or any PSR-18 client. ## Install [#install] The SDKs aren't on npm, PyPI or Packagist yet. Until they are, install them from the Druckling source repository as shown below. Each SDK page has the full steps. ```bash tab="TypeScript" git clone https://github.com/vulpery/druckling.git cd druckling/src/integrations/sdk-typescript npm install && npm run build && npm pack # then, in your project npm install /path/to/druckling-sdk-0.1.0.tgz ``` ```bash tab="Python" pip install "git+https://github.com/vulpery/druckling.git#subdirectory=src/integrations/sdk-python" ``` ```bash tab="PHP" git clone https://github.com/vulpery/druckling.git # then, in your project composer config repositories.druckling path /path/to/druckling/src/integrations/sdk-php composer require druckling/druckling-php:@dev ``` ## Render your first document [#render-your-first-document] Every workspace starts with the `invoice-standard` template published, so this works with a fresh [test key](/docs/concepts/test-mode): ```ts tab="TypeScript" import Druckling from "@druckling/sdk"; const druckling = new Druckling(); // reads DRUCKLING_API_KEY const document = await druckling.documents.create({ template: "invoice-standard", data: { invoice: { number: "INV-2041", due_date: "2026-11-22" }, customer: { name: "Northwind Ltd.", address: "12 Pier St, Leeds" }, line_items: [{ description: "Design system audit", qty: 12, rate: 180, amount: 2160 }], totals: { subtotal: 2160, tax: 172.8, amount: 2332.8 }, }, }); console.log(document.status, document.url); // rendered https://… ``` ```python tab="Python" from druckling import Druckling client = Druckling() # reads DRUCKLING_API_KEY document = client.documents.create( template="invoice-standard", data={ "invoice": {"number": "INV-2041", "due_date": "2026-11-22"}, "customer": {"name": "Northwind Ltd.", "address": "12 Pier St, Leeds"}, "line_items": [{"description": "Design system audit", "qty": 12, "rate": 180, "amount": 2160}], "totals": {"subtotal": 2160, "tax": 172.8, "amount": 2332.8}, }, ) print(document.status, document.url) # rendered https://… ``` ```php tab="PHP" documents->create( template: 'invoice-standard', data: [ 'invoice' => ['number' => 'INV-2041', 'due_date' => '2026-11-22'], 'customer' => ['name' => 'Northwind Ltd.', 'address' => '12 Pier St, Leeds'], 'line_items' => [['description' => 'Design system audit', 'qty' => 12, 'rate' => 180, 'amount' => 2160]], 'totals' => ['subtotal' => 2160, 'tax' => 172.8, 'amount' => 2332.8], ], ); echo $document->status, ' ', $document->url; // rendered https://… ``` ## What the SDKs cover [#what-the-sdks-cover] The SDKs implement the API resources you use most. For the others, call the REST API directly with the same API key. | API resource | Endpoints | In the SDKs | | --- | --- | --- | | [Documents](/docs/api-reference/documents/create) | create, get, list | Yes. PNG page and scale options (`image`) aren't supported yet. | | [Templates](/docs/api-reference/templates/get) | list, get | Yes | | [Webhook endpoints](/docs/api-reference/webhooks/create) | create, list, get, delete | Yes. The `batch.completed` event isn't in the SDKs' event types yet. | | [Embedded editor sessions](/docs/api-reference/embedded-editor/create) | create, revoke | Yes | | [Batches](/docs/api-reference/batches/create) | create, list, get, documents, cancel | Not yet: use the REST API ([guide](/docs/guides/batches)) | | [Share links](/docs/api-reference/share-links/create) | create, list, revoke | Not yet: use the REST API ([guide](/docs/concepts/share-links)) | On top of the endpoints, each SDK adds: | Task | TypeScript | Python | PHP | | --- | --- | --- | --- | | Wait for an async render | `documents.wait(doc)` | `documents.wait(doc)` | `documents->wait($doc)` | | Download the file | `documents.download(doc)` | `documents.download(doc)`, `documents.download_to(doc, path)` | `documents->download($doc)`, `documents->downloadTo($doc, $path)` | | Walk every page of a list | `for await (const doc of documents.list())` | `for doc in documents.list()` | `foreach ($druckling->documents->list() as $doc)` | | Verify a webhook | `verifyWebhook(body, headers, secret)` | `verify_webhook(body, headers, secret)` | `Webhook::verify($body, $headers, $secret)` | | Sign a test webhook | `signWebhook(secret, id, timestamp, body)` | `sign_webhook(secret, msg_id, timestamp, body)` | `Webhook::sign($secret, $msgId, $timestamp, $body)` | ## Shared behavior [#shared-behavior] The three SDKs follow the same rules, so you can move between them without surprises. ### Configuration [#configuration] - **API key**: passed to the constructor, or read from the `DRUCKLING_API_KEY` environment variable. It's sent as `Authorization: Bearer …`. Creating a client without a key throws right away. - **Base URL**: passed to the constructor, or read from `DRUCKLING_BASE_URL`, defaulting to `https://druckling-nine.vercel.app`. It works with or without a trailing `/v1`; the SDK adds `/v1` itself. - **Mode**: the key decides it. `dr_test_…` keys work in test mode, `dr_live_…` keys in live mode. See [Test mode](/docs/concepts/test-mode). Keep API keys on your server. Never ship them to a browser or mobile app; for in-browser template editing, use [embedded editor sessions](/docs/guides/embedded-editor) instead. ### Retries [#retries] Each request is retried up to 2 times by default (`maxRetries` / `max_retries`, `0` turns retries off): - `429 rate_limited` is retried for every request, including renders: a rate-limited request produced no file and counted nothing toward your quota. - `429 quota_exceeded` is never retried. Your plan's document quota is used up, so the SDK throws a quota error right away. See [Plans and limits](/docs/concepts/plans-and-limits). - `408`, `5xx`, timeouts and connection errors are retried for `GET` and `DELETE` requests only. - `POST` requests (rendering a document, creating a webhook endpoint or an editor session) are **not** retried after a `5xx`, 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. Catch the error and decide yourself, for example by [listing recent documents](/docs/api-reference/documents/list) first. Waits grow exponentially from 0.5 seconds to at most 8 seconds, with jitter. When a response carries a `Retry-After` header of 60 seconds or less, the SDK waits that long instead; a longer `Retry-After` is returned to you as an error without retrying. ### Timeouts [#timeouts] The default timeout is 60 seconds per attempt; each SDK's page explains exactly what it covers. Synchronous renders happen inside the request, so leave room for large documents, or render them [asynchronously](/docs/concepts/documents). ### Waiting for async renders [#waiting-for-async-renders] With `async: true` (`async_=True` in Python), `documents.create` returns at once with status `queued`. The wait helper polls the document every second for up to 120 seconds. It returns the document once it's `rendered`, throws a document-failed error when it ends `failed` or `expired`, and a wait-timeout error when time runs out. Every poll is an API request, so for long queues prefer [webhooks](/docs/guides/webhooks). ### Downloads [#downloads] The download helpers fetch the file (PDF, PNG or XML) from the document's signed `url`. Your API key isn't sent to that URL. Pass a document ID instead of a document to get a fresh signed URL first; signed URLs stop working after at most 7 days. ### Errors [#errors] Every SDK has one error class per kind of failure, all under one base class. API errors carry the HTTP `status`, Druckling's error `code`, the `message`, the offending `field`, a list of field errors (for example every missing field of a payload), the ID of the failed document for validation failures, and the request ID. See [Errors](/docs/concepts/errors) for the codes. ### Webhook verification [#webhook-verification] Webhooks follow the [Standard Webhooks](https://www.standardwebhooks.com/) spec. The verify helpers check the HMAC-SHA256 signature against the raw request body, reject timestamps more than 5 minutes off, accept any of several signatures (so secret rotation needs no downtime), and return the parsed event. See [Webhooks](/docs/guides/webhooks). ## Other integrations [#other-integrations] Let AI assistants render documents and edit templates through Druckling's hosted MCP server. Render documents and react to document events in n8n workflows. # PHP (/docs/sdks/php) > Render documents, wait for async renders, verify webhooks and create embedded editor sessions with the official PHP SDK. `druckling/druckling-php` is the official PHP client for the Druckling API. It has typed, readonly models and one exception class per kind of error. It needs nothing beyond `ext-curl` and `ext-json`, and can send its requests through any PSR-18 client instead. ## Install [#install] Requirements: - PHP 8.1 or later with `ext-curl` and `ext-json`. - Optional: a PSR-18 HTTP client and PSR-17 factories, to use [`Psr18Transport`](#psr-18-clients). The package isn't on Packagist yet. Install it from the Druckling source repository as a Composer path repository: ```bash git clone https://github.com/vulpery/druckling.git # then, in your project composer config repositories.druckling path /path/to/druckling/src/integrations/sdk-php composer require druckling/druckling-php:@dev ``` Composer symlinks path repositories by default. If your build can't follow the link (a Docker image, for example), set `"options": { "symlink": false }` on the `druckling` repository in `composer.json` to copy the files instead. Then create a key under **Developers › API keys** and expose it as `DRUCKLING_API_KEY`. ## Configuration [#configuration] ```php use Druckling\Druckling; $druckling = new Druckling( apiKey: 'dr_test_...', baseUrl: 'https://druckling-nine.vercel.app', timeout: 60.0, maxRetries: 2, defaultHeaders: ['X-Correlation-Id' => 'checkout-42'], ); ``` | Argument | Default | Notes | | --- | --- | --- | | `apiKey` | `DRUCKLING_API_KEY` | An `dr_test_…` or `dr_live_…` key, sent as `Authorization: Bearer …`. Read with `getenv()`, then `$_ENV` and `$_SERVER`. | | `baseUrl` | `DRUCKLING_BASE_URL`, then `https://druckling-nine.vercel.app` | With or without a trailing `/v1`. Must be an `http` or `https` URL. | | `timeout` | `60.0` | Seconds per HTTP attempt with the built-in transport, see [Retries and timeouts](#retries-and-timeouts). | | `maxRetries` | `2` | Retries after the first attempt. `0` turns retries off. | | `transport` | `new CurlTransport()` | Any `Druckling\Http\Transport`, such as `Psr18Transport`. | | `defaultHeaders` | `[]` | Extra headers on every API request. | Use named arguments. The constructor throws a `DrucklingException` without an API key, for an invalid base URL, a `timeout` of 0 or less, or a negative `maxRetries`. - `$druckling->withOptions(timeout: 120.0, maxRetries: 4)` returns a copy with other settings that shares the transport. - `$druckling->isTestMode()` is `true` for `dr_test_…` keys. `$druckling->baseUrl()` is the origin requests go to, without `/v1`. Once you cache the configuration (`php artisan config:cache`), Laravel no longer loads `.env`, so the SDK can't read `DRUCKLING_API_KEY` from that file. Add the key to `config/services.php` and pass it in a service provider instead: `$this->app->singleton(Druckling::class, fn () => new Druckling(apiKey: config('services.druckling.key')));` ### Built-in curl transport [#built-in-curl-transport] `CurlTransport` reuses one curl handle, so connections stay open between requests. Its connect timeout is 10 seconds; change it with `new CurlTransport(connectTimeout: 5.0)` and pass that as `transport`. ### PSR-18 clients [#psr-18-clients] To send requests through Guzzle, Symfony HttpClient or any other PSR-18 client (for proxies, middleware or tracing), wrap it in `Psr18Transport` with PSR-17 request and stream factories: ```bash composer require guzzlehttp/guzzle ``` ```php use GuzzleHttp\Client; use GuzzleHttp\Psr7\HttpFactory; use Druckling\Http\Psr18Transport; use Druckling\Druckling; $factory = new HttpFactory(); $druckling = new Druckling(transport: new Psr18Transport(new Client(['timeout' => 60]), $factory, $factory)); ``` With a PSR-18 client, timeouts are whatever that client is configured with; the SDK's `timeout` doesn't apply. Network errors and timeouts from the client both surface as `ConnectionException`. ## Render a document [#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: ```php ['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 = $druckling->documents->create( template: 'invoice-standard', data: $invoice, filename: 'INV-2041.pdf', ); echo $document->id, ' ', $document->status, ' ', $document->pages, PHP_EOL; // pdf_… rendered 1 $druckling->documents->downloadTo($document, __DIR__ . '/INV-2041.pdf'); ``` The arguments are `template` (slug), `data`, and optionally `version` (a published version number, default `'latest'`), `filename`, `async`, `language` and `format`. `data` is sent as JSON. An empty top-level array becomes `{}`; for an empty object deeper in the payload, pass `new \stdClass()`. It must match the template's schema; `$druckling->templates->get('invoice-standard')->sampleData` is a payload that renders. See [Variables](/docs/concepts/variables). The returned `Druckling\Model\Document` has the API's fields as camelCase properties (`sizeBytes`, `contentType`, `testMode`, …), with `createdAt` and `expiresAt` as `DateTimeImmutable`. `isRendered()`, `isFailed()` (failed or expired) and `isFinal()` check the status; the `Druckling\Model\DocumentStatus` constants name the values. `$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](/docs/api-reference/documents/get) for every field. ## Render asynchronously and wait [#render-asynchronously-and-wait] Pass `async: true` 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](#webhooks): ```php use Druckling\Exception\DocumentFailedException; use Druckling\Exception\WaitTimeoutException; $queued = $druckling->documents->create(template: 'invoice-standard', data: $invoice, async: true); echo $queued->status; // queued try { $document = $druckling->documents->wait($queued, timeout: 120.0, interval: 1.0); $pdf = $druckling->documents->download($document); } catch (DocumentFailedException $e) { error_log('Render failed: ' . ($e->document->error?->message ?? $e->document->status)); } catch (WaitTimeoutException $e) { error_log("Still {$e->document->status}; check again later"); } ``` `wait(Document|string $document, float $timeout = 120.0, float $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 throws `DocumentFailedException` when the document ends `failed` or `expired` (`$e->document` holds it), and `WaitTimeoutException` when the next poll would pass `$timeout` (`$e->document` is the last state seen). Waiting blocks the PHP process, and each poll is an API request that counts toward your key's rate limit. In a web request, prefer [webhooks](#webhooks) or a queued job. ## Download the file [#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 as a string. - `documents->downloadTo($document, $path)` writes it to a file, and throws a `DrucklingException` if it can't. Both fetch the file from the document's signed `url`; your API key isn't sent there. ```php $bytes = $druckling->documents->download($document); $druckling->documents->downloadTo($document, __DIR__ . '/' . $document->filename); ``` - Pass a document ID instead of a `Document` to 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 at `expiresAt`. - A document that is `failed` or `expired` throws `DocumentFailedException`. One that is still `queued` or `rendering` throws a `DrucklingException`; call `wait()` first. - A failed request to the signed URL throws an `ApiException` with `errorCode` `download_failed`. ## PNG and XML output [#png-and-xml-output] Pass `format: 'png'` to render the first page as a PNG at 144 dpi instead of a PDF: ```php $preview = $druckling->documents->create(template: 'invoice-standard', data: $invoice, format: 'png'); echo $preview->contentType, ' ', $preview->pages; // image/png 1 $druckling->documents->downloadTo($preview, __DIR__ . '/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, send the request with the SDK's transport and hand the result to its helpers: ```php use Druckling\Exception\ApiException; use Druckling\Http\CurlTransport; use Druckling\Http\Request; use Druckling\Model\Document; $response = (new CurlTransport())->send(new Request( 'POST', 'https://druckling-nine.vercel.app/v1/documents', ['Authorization' => 'Bearer ' . getenv('DRUCKLING_API_KEY'), 'Content-Type' => 'application/json'], json_encode( ['template' => 'invoice-standard', 'data' => $invoice, 'format' => 'png', 'image' => ['page' => 1, 'scale' => 4]], JSON_THROW_ON_ERROR, ), 60.0, )); if (!$response->isSuccessful()) { throw ApiException::fromResponse($response); // the same typed exceptions as the SDK } $hiRes = Document::fromArray(json_decode($response->body, true, 512, JSON_THROW_ON_ERROR)); $druckling->documents->downloadTo($hiRes, __DIR__ . '/INV-2041@4x.png'); ``` XML output is for e-invoice templates set to XRechnung or Peppol BIS: they render `format: 'xml'` by default, `contentType` 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 throws a `ValidationException` with `$e->field === 'format'`. See [PNG output](/docs/guides/png-output) and [E-invoicing](/docs/guides/e-invoicing). ## Languages [#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: ```php $template = $druckling->templates->get('invoice-standard'); $template->language; // 'en' $template->languages; // ['en', 'de'], default first $rechnung = $druckling->documents->create( template: 'invoice-standard', data: $invoice, filename: 'RE-2041.pdf', language: 'de', ); echo $rechnung->language; // de ``` Without `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 throws a `ValidationException` with `$e->field === 'language'`. See [Languages](/docs/guides/languages). ## List documents [#list-documents] `documents->list()` fetches one page of documents, newest first, as a `CursorPage`. Iterating the page walks every matching document, fetching the following pages as you go: ```php use Druckling\Model\DocumentStatus; foreach ($druckling->documents->list(status: DocumentStatus::FAILED, template: 'invoice-standard') as $document) { echo $document->id, ' ', $document->createdAt->format('c'), ' ', $document->error?->message, PHP_EOL; } $page = $druckling->documents->list(limit: 25); $page->data; // up to 25 documents $page->nextCursor; // pass as list(cursor: …) to resume later, or null $page->hasNextPage(); // bool $page->nextPage(); // the next CursorPage, or null ``` Filters: `limit` (1 to 100, default 25), `cursor`, `status` (`queued`, `rendering`, `rendered`, `failed`, `expired`) and `template` (slug). A test key lists test documents, a live key live ones. See [List documents](/docs/api-reference/documents/list). Fetch one document with `documents->get('pdf_…')`. ## Templates [#templates] ```php foreach ($druckling->templates->list() as $template) { echo $template->slug, ' ', $template->status, ' v', $template->latestVersion ?? '-', PHP_EOL; } $template = $druckling->templates->get('invoice-standard'); $template->requiredFields; // ['invoice.number', 'invoice.due_date', 'customer.name', …, 'line_items[].qty', …] $template->jsonSchema; // the JSON Schema `data` is validated against $template->sampleData; // a payload that renders ``` - Reading templates needs a **Full access** key; a **Render only** key gets a `PermissionDeniedException`. - `templates->list()` returns a `ListResponse` with every template of the workspace, drafts included. It isn't paginated: iterate it, `count()` it, or read `->data`. See [List templates](/docs/api-reference/templates/list) and [Retrieve a template](/docs/api-reference/templates/get). - `jsonSchema`, `sampleData`, `requiredFields` and `languages` come from the latest published version, or from the draft if the template was never published. - Only published templates render (`$template->isPublished()`). Pin a version with `documents->create(..., version: 3)`. ## Errors [#errors] Every exception the SDK throws extends `Druckling\Exception\DrucklingException`, itself a `RuntimeException`. Errors from the API are `ApiException` subclasses. All classes live in `Druckling\Exception`: ```text DrucklingException ├── ApiException │ ├── ValidationException │ ├── AuthenticationException │ ├── PermissionDeniedException │ ├── NotFoundException │ ├── ConflictException │ ├── RenderException │ ├── RateLimitException │ │ └── QuotaExceededException │ └── ServerException ├── ConnectionException │ └── TimeoutException ├── DocumentFailedException ├── WaitTimeoutException └── WebhookVerificationException ``` The class follows Druckling's error code first, then the HTTP status: | Exception | When | | --- | --- | | `ValidationException` | `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`). | | `AuthenticationException` | `401` `unauthorized`: missing, invalid or revoked API key. | | `PermissionDeniedException` | `403` `forbidden`: the key lacks a permission, for example a Render only key reading templates or managing webhooks. | | `NotFoundException` | `404` `not_found`: unknown document, template, webhook endpoint or editor session, or a template without a published version. | | `ConflictException` | `409` `conflict` or `invalid_state`: the resource's current state doesn't allow the request. | | `RenderException` | `render_failed` (`422`) or `render_timeout` (`504`): the template couldn't be rendered, or took too long. | | `RateLimitException` | `429` `rate_limited`, after the automatic retries. | | `QuotaExceededException` | `429` `quota_exceeded`: the plan's document quota is used up. Never retried. | | `ServerException` | Any other `5xx`. | | `ApiException` | 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`). | | `ConnectionException` | No HTTP response: DNS, TLS or network failure. `TimeoutException` when the built-in transport timed out. | | `DocumentFailedException` | `wait()` or a download found the document `failed` or `expired`. `$e->document` holds it. | | `WaitTimeoutException` | `wait()` ran out of time. `$e->document` is the last state seen. | | `WebhookVerificationException` | A webhook's signature, timestamp or body didn't verify. | An `ApiException` has `getMessage()`, `getCode()` (the HTTP status) and these readonly properties: | Property | Type | Notes | | --- | --- | --- | | `status` | `int` | HTTP status. | | `errorCode` | `string` | Druckling's error code, for example `schema_validation_failed`. See [Errors](/docs/concepts/errors). | | `field` | `?string` | Dotted path of the offending field, for example `customer.name` or `language`. | | `errors` | `list` | Every offending field, with `field`, `message` and `rule` (a broken e-invoice business rule such as `BR-CO-25`, else `null`). | | `documentId` | `?string` | The failed document recorded for a payload that didn't validate. | | `retryAfter` | `?float` | Seconds from the response's `Retry-After` header, when it has one. | | `requestId` | `?string` | Quote it when you contact support. | | `body` | `array`, `string` or `null` | Decoded JSON body, or the raw text when it isn't JSON. | | `headers` | `array` | Response headers, with lowercase names. | `ValidationException::messagesByField()` groups the messages by field, for showing them next to form inputs. ```php use Druckling\Exception\ApiException; use Druckling\Exception\QuotaExceededException; use Druckling\Exception\RateLimitException; use Druckling\Exception\ValidationException; try { $druckling->documents->create(template: 'invoice-standard', data: ['customer' => ['name' => 'Northwind Ltd.']]); } catch (ValidationException $e) { echo $e->getMessage(), PHP_EOL; // Required field invoice was missing from the request payload foreach ($e->errors as $error) { echo "{$error->field}: {$error->message}", PHP_EOL; } // invoice: missing required field invoice // line_items: missing required field line_items // totals: missing required field totals // customer.address: missing required field customer.address $e->messagesByField(); // ['invoice' => ['missing required field invoice'], 'line_items' => [...], …] $e->documentId; // pdf_… (the failed document is kept for your logs) } catch (QuotaExceededException $e) { notifyBilling($e->getMessage()); } catch (RateLimitException $e) { requeueLater($invoice); } catch (ApiException $e) { error_log("Druckling {$e->status} {$e->errorCode}: {$e->getMessage()} ({$e->requestId})"); } ``` Catch `QuotaExceededException` before `RateLimitException`, since it's a subclass. ## Retries and timeouts [#retries-and-timeouts] The client retries failed requests up to `maxRetries` times (default 2): - `429 rate_limited` is retried for every request, including renders: a rate-limited request produced no file. - `429 quota_exceeded` is never retried; you get a `QuotaExceededException` right away. - `408`, `5xx`, timeouts and connection errors are retried for `GET` and `DELETE` requests only, including downloads from signed URLs. - `POST` requests (`documents->create()`, `webhookEndpoints->create()`, `embedSessions->create()`) aren't retried after a `5xx`, 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. Catch `ServerException` and `ConnectionException` and decide yourself, for example by checking `documents->list()` 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 thrown to you without retrying. The SDK waits with `usleep()`, so retries block the process. With the built-in transport, `timeout` (default 60 seconds) limits each attempt as a whole, and connecting is limited to 10 seconds. Synchronous renders happen inside the request, so leave room for large documents, or render them with `async: true`. With a PSR-18 client, its own timeouts apply. ## Webhooks [#webhooks] Druckling can call your HTTPS endpoint when a document is rendered, fails or expires. Deliveries follow the [Standard Webhooks](https://www.standardwebhooks.com/) spec: `webhook-id`, `webhook-timestamp` and `webhook-signature` headers, signed with HMAC-SHA256 over the raw body. ### Verify signatures [#verify-signatures] `Webhook::verify()` checks the signature and the timestamp, then returns a typed `WebhookEvent`. Pass the **raw** body, before any JSON decoding; re-encoded JSON won't match the signature. ```php tab="Plain PHP" type === WebhookEvent::DOCUMENT_RENDERED && $event->document !== null) { saveInvoice($event->document->id, $event->document->url); } http_response_code(204); ``` ```php tab="Laravel" use Illuminate\Http\Request; use Druckling\Exception\WebhookVerificationException; use Druckling\Webhook; Route::post('/webhooks/druckling', function (Request $request) { try { $event = Webhook::verify($request->getContent(), $request->headers->all(), config('services.druckling.webhook_secret')); } catch (WebhookVerificationException) { abort(400); } if ($event->document !== null) { ProcessRenderedDocument::dispatch($event->type, $event->document->id); } return response()->noContent(); }); ``` In Laravel, register the route outside the `web` middleware group, for example in `routes/api.php`, so CSRF protection doesn't reject Druckling's requests. In Symfony, use `$request->getContent()` and `$request->headers->all()` the same way; with a PSR-7 request, `(string) $request->getBody()` and `$request->getHeaders()`. `Webhook::verify(string $rawBody, array $headers, string $secret, int $tolerance = 300, ?int $now = null)`: | Parameter | Notes | | --- | --- | | `$rawBody` | The raw request body. | | `$headers` | `getallheaders()`, `$_SERVER` (`HTTP_WEBHOOK_ID` …), a PSR-7 `getHeaders()` array, or Symfony and Laravel's `$request->headers->all()`. Names are matched case-insensitively. | | `$secret` | The endpoint's `whsec_…` signing secret. | | `$tolerance` | Maximum age and clock skew of `webhook-timestamp`, in seconds. Default `300`. | | `$now` | Unix time to check against, for tests. | The `WebhookEvent` has `id`, `object`, `type`, `createdAt` (`DateTimeImmutable`), `testMode`, `data` (the raw `data` array) and `document`: a `Document` for `document.rendered`, `document.failed` and `document.expired`, otherwise `null` (`isDocumentEvent()` checks it). The constants `WebhookEvent::DOCUMENT_RENDERED`, `DOCUMENT_FAILED`, `DOCUMENT_EXPIRED` and `WEBHOOK_PING` name the types. - **Duplicates**: a delivery can arrive more than once. Use `$event->id` (the same as the `webhook-id` header) to ignore repeats; a resent event keeps its ID. - **Answer fast**: respond with a `2xx` within 10 seconds and do slow work in a queue. Other answers and timeouts are retried for about 8.6 hours. Don't answer `410 Gone` unless 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.ping` event; `$event->data` is `['object' => 'ping', 'endpoint_id' => …, 'message' => …]` and `$event->document` is `null`. - **Batches**: `batch.completed` events verify like any other; `$event->document` is `null` and `$event->data` is the batch. There's no constant for it yet: compare `$event->type` with `'batch.completed'`. `Webhook::verifySignature()` takes the same arguments and checks the signature without decoding the body. To test your handler, `Webhook::sign($secret, $msgId, $timestamp, $body)` returns the `webhook-signature` value Druckling would send (`$timestamp` in Unix seconds). ### Manage webhook endpoints [#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. ```php use Druckling\Model\WebhookEvent; $endpoint = $druckling->webhookEndpoints->create( url: 'https://example.com/webhooks/druckling', events: [WebhookEvent::DOCUMENT_RENDERED, WebhookEvent::DOCUMENT_FAILED], description: 'Invoice mailer', ); echo $endpoint->id, ' ', $endpoint->secret; // whe_… whsec_… foreach ($druckling->webhookEndpoints->list() as $e) { echo $e->id, ' ', $e->url, ' ', implode(',', $e->events), PHP_EOL; } $druckling->webhookEndpoints->get($endpoint->id); $druckling->webhookEndpoints->delete($endpoint->id); // DeletedObject with ->deleted === true ``` The `secret` is returned only by `create()`: store it now, for example as `DRUCKLING_WEBHOOK_SECRET`. The URL must be a public `https://` URL. See [Webhooks](/docs/guides/webhooks) for the event payloads and delivery details, and the [webhook endpoint reference](/docs/api-reference/webhooks/create) for every field. ## Embedded editor sessions [#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: ```php use Druckling\Druckling; $druckling = new Druckling(); // Your endpoint, e.g. POST /template-editor, after your own login check $session = $druckling->embedSessions->create( template: 'invoice-standard', permissions: ['publish' => true], user: ['id' => (string) $user->id, 'name' => $user->name], theme: ['mode' => 'system', 'accent' => '#0f766e'], expiresIn: 1800, ); header('Content-Type: application/json'); header('Cache-Control: no-store'); echo json_encode(['url' => $session->url]); ``` | 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. | | `expiresIn` | `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](/docs/guides/embedded-editor), and the reference for [creating](/docs/api-reference/embedded-editor/create) and [revoking](/docs/api-reference/embedded-editor/revoke) sessions. - The `url` carries the session token in its fragment (`#token=…`). Give it only to the signed-in user's browser; never log, cache or store it. Only `create()` returns it. - `$druckling->embedSessions->revoke($session->id)` ends a session right away, for example when the user signs out. It returns the session with `status` `revoked` (`EmbedSession::STATUS_REVOKED`) and a `null` `url`. Revoking twice is fine. - `create()` throws `ConflictException` (`invalid_state`) until an origin is allowed in **Settings › Embed**, `PermissionDeniedException` for a Render only key, `ValidationException` for bad options, and `RateLimitException` beyond about 60 sessions a minute per workspace. ## Test and live keys [#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 has `testMode` set to `true`. - `dr_live_…` keys are for production. Live renders count toward your plan's quota. `$druckling->isTestMode()` tells you which one a client uses. See [Test mode](/docs/concepts/test-mode). ## Next steps [#next-steps] Every endpoint, field and error of the REST API the SDK wraps. Event payloads, delivery retries and secret rotation. What each error code means and how to handle it. # Python (/docs/sdks/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`](https://www.python-httpx.org/). ## Install [#install] Requirements: - Python 3.9 or later. - `httpx` 0.23 or later (below 1.0), installed automatically. The package isn't on PyPI yet. Install it from the Druckling source repository: ```bash 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: ```text title="requirements.txt" druckling @ git+https://github.com/vulpery/druckling.git#subdirectory=src/integrations/sdk-python ``` Then create a key under **Developers › API keys** and export it: ```bash export DRUCKLING_API_KEY=dr_test_... ``` ## Configuration [#configuration] ```python 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](#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 call `client.close()` to release its connections. The SDK only closes HTTP clients it created itself. - `client.mode` is `"test"` for `dr_test_…` keys, `"live"` for `dr_live_…` keys, and `"unknown"` otherwise. `client.base_url` is the origin requests go to, without `/v1`. ### Custom HTTP client [#custom-http-client] Pass an `httpx` client to control proxies, TLS or connection limits: ```python 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 [#async-client] `AsyncDruckling` takes the same options (with an `httpx.AsyncClient` as `http_client`) and has the same resources and methods; you `await` them: ```python 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 [#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: ```python tab="Sync" 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") ``` ```python tab="Async" from druckling import AsyncDruckling async def render_invoice(invoice: dict) -> None: async with AsyncDruckling() as client: document = await client.documents.create(template="invoice-standard", filename="INV-2041.pdf", data=invoice) print(document.id, document.status, document.pages) # pdf_… rendered 1 await 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](/docs/concepts/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](/docs/api-reference/documents/get) for every field. ## Render asynchronously and wait [#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](#webhooks): ```python tab="Sync" 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") ``` ```python tab="Async" queued = await client.documents.create(template="invoice-standard", data=invoice, async_=True) document = await client.documents.wait(queued, timeout=120, interval=1) pdf = await client.documents.download(document) ``` `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 [#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 as `bytes`. - `documents.download_to(document, path)` streams it to a file and returns the `pathlib.Path`. Both fetch the file from the document's signed `url`; your API key isn't sent there. ```python 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 `Document` to 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 at `expires_at`. - A document that is `failed` or `expired` raises `DocumentFailedError`. One that is still `queued` or `rendering` raises `DrucklingError`; call `wait` first. - A failed request to the signed URL raises `APIError` with `code == "download_failed"`. ## PNG and XML output [#png-and-xml-output] Pass `format="png"` to render the first page as a PNG at 144 dpi instead of a PDF: ```python 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: ```python 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](/docs/guides/png-output) and [E-invoicing](/docs/guides/e-invoicing). ## Languages [#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: ```python 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) # de ``` Without `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](/docs/guides/languages). ## List documents [#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: ```python tab="Sync" 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 None ``` ```python tab="Async" page = await client.documents.list(status="failed") async for document in page: print(document.id, document.error) next_page = await page.next_page() # the next AsyncCursorPage, or None ``` Filters: `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](/docs/api-reference/documents/list). ## Templates [#templates] ```python 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 a `ListResponse` with every template of the workspace, drafts included. It isn't paginated: iterate it, index it or use `len()`, or read `.data`. See [List templates](/docs/api-reference/templates/list) and [Retrieve a template](/docs/api-reference/templates/get). - `json_schema`, `sample_data`, `required_fields` and `languages` come 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 [#errors] Every exception the SDK raises derives from `druckling.DrucklingError`. Errors from the API are `APIError` subclasses: ```text DrucklingError ├── APIError │ ├── ValidationError │ ├── AuthenticationError │ ├── PermissionDeniedError │ ├── NotFoundError │ ├── ConflictError │ ├── RenderError │ ├── RateLimitError │ │ └── QuotaExceededError │ └── ServerError ├── APIConnectionError │ └── APITimeoutError ├── DocumentFailedError ├── WaitTimeoutError └── WebhookVerificationError ``` The 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](/docs/concepts/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. | ```python 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 [#retries-and-timeouts] The client retries failed requests up to `max_retries` times (default 2): - `429 rate_limited` is retried for every request, including renders: a rate-limited request produced no file. - `429 quota_exceeded` is never retried; you get `QuotaExceededError` right away. - `408`, `5xx`, timeouts and connection errors are retried for `GET` and `DELETE` requests only, including downloads from signed URLs. - `POST` requests (`documents.create`, `webhook_endpoints.create`, `embed_sessions.create`) aren't retried after a `5xx`, 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. Catch `ServerError` and `APIConnectionError` and 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 [#webhooks] Druckling can call your HTTPS endpoint when a document is rendered, fails or expires. Deliveries follow the [Standard Webhooks](https://www.standardwebhooks.com/) spec: `webhook-id`, `webhook-timestamp` and `webhook-signature` headers, signed with HMAC-SHA256 over the raw body. ### Verify signatures [#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. ```python import os from druckling import WebhookVerificationError, verify_webhook SECRET = os.environ["DRUCKLING_WEBHOOK_SECRET"] # whsec_… ``` ```python tab="Flask" 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 ``` ```python tab="FastAPI" from fastapi import FastAPI, HTTPException, Request app = FastAPI() @app.post("/webhooks/druckling", status_code=204) async def druckling_webhook(request: Request) -> None: try: event = verify_webhook(await request.body(), request.headers, SECRET) except WebhookVerificationError: raise HTTPException(status_code=400) if event.type == "document.failed" and event.document and event.document.error: alert_ops(event.document.error.message) ``` ```python tab="Django" from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST @csrf_exempt @require_POST def druckling_webhook(request): try: event = verify_webhook(request.body, request.headers, SECRET) except WebhookVerificationError: return HttpResponse(status=400) if event.document: process_document.delay(event.type, event.document.id) return HttpResponse(status=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 the `webhook-id` header) to ignore repeats; a resent event keeps its ID. - **Answer fast**: respond with a `2xx` within 10 seconds and do slow work in a queue. Other answers and timeouts are retried for about 8.6 hours. Don't answer `410 Gone` unless 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.ping` event; `event.data` is `{"object": "ping", "endpoint_id": …, "message": …}` and `event.document` is `None`. - **Batches**: `batch.completed` events verify like any other; `event.document` is `None` and `event.data` is the batch. The SDK's `WebhookEventType` doesn't list `batch.completed` yet, 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 [#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. ```python 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](/docs/guides/webhooks) for the event payloads and delivery details, and the [webhook endpoint reference](/docs/api-reference/webhooks/create) for every field. ## Embedded editor sessions [#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: ```python 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](/docs/guides/embedded-editor), and the reference for [creating](/docs/api-reference/embedded-editor/create) and [revoking](/docs/api-reference/embedded-editor/revoke) sessions. - The `url` carries the session token in its fragment (`#token=…`). Give it only to the signed-in user's browser; never log, cache or store it. Only `create` returns it, and it's left out of the model's `repr()`. - `client.embed_sessions.revoke(session.id)` ends a session right away, for example when the user signs out. It returns the session with `status == "revoked"` and `url` set to `None`. Revoking twice is fine. - `create` raises `ConflictError` (`invalid_state`) until an origin is allowed in **Settings › Embed**, `PermissionDeniedError` for a Render only key, `ValidationError` for bad options, and `RateLimitError` beyond about 60 sessions a minute per workspace. ## Test and live keys [#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 has `test_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](/docs/concepts/test-mode). ## Next steps [#next-steps] Every endpoint, field and error of the REST API the SDK wraps. Event payloads, delivery retries and secret rotation. What each error code means and how to handle it. # TypeScript (/docs/sdks/typescript) > Render documents, wait for async renders, verify webhooks and create embedded editor sessions with the official TypeScript SDK. `@druckling/sdk` is the official TypeScript and JavaScript client for the Druckling API. It's built on `fetch` and Web Crypto with no runtime dependencies, so the same code runs on Node.js, Bun, Deno, Cloudflare Workers and Vercel Functions. Requests, responses, webhook events and errors are typed. ## Install [#install] Requirements: - Node.js 20 or later, or any runtime with `fetch` and Web Crypto (`globalThis.crypto.subtle`). - No runtime dependencies. The package ships ESM and CommonJS builds with type declarations. The package isn't on npm yet. Build it from the Druckling source repository and install the tarball: ### Build the package [#build-the-package] ```bash git clone https://github.com/vulpery/druckling.git cd druckling/src/integrations/sdk-typescript npm install && npm run build && npm pack ``` `npm pack` writes `druckling-sdk-0.1.0.tgz` to that folder. ### Add it to your project [#add-it-to-your-project] ```bash npm install /path/to/druckling-sdk-0.1.0.tgz ``` ### Set your API key [#set-your-api-key] Create a key under **Developers › API keys** and export it: ```bash export DRUCKLING_API_KEY=dr_test_... ``` Import the client as the default export or by name. CommonJS works too: ```ts import Druckling from "@druckling/sdk"; // or: import { Druckling } from "@druckling/sdk"; // or: const { Druckling } = require("@druckling/sdk"); ``` ## Configuration [#configuration] ```ts import { Druckling } from "@druckling/sdk"; const druckling = new Druckling({ apiKey: process.env.DRUCKLING_API_KEY, baseUrl: "https://druckling-nine.vercel.app", timeoutMs: 60_000, maxRetries: 2, }); ``` | Option | Default | Notes | | --- | --- | --- | | `apiKey` | `DRUCKLING_API_KEY` | An `dr_test_…` or `dr_live_…` key, sent as `Authorization: Bearer …`. The constructor throws a `DrucklingError` when there's none. | | `baseUrl` | `DRUCKLING_BASE_URL`, then `https://druckling-nine.vercel.app` | With or without a trailing `/v1`. | | `timeoutMs` | `60000` | Per HTTP attempt, see [Retries and timeouts](#retries-and-timeouts). | | `maxRetries` | `2` | Retries after the first attempt. `0` turns retries off. | | `fetch` | `globalThis.fetch` | Your own `fetch` implementation. | | `defaultHeaders` | none | Extra headers on every API request. | Environment variables are read where `process.env` exists (Node.js, Bun). In other runtimes, such as Cloudflare Workers, pass `apiKey` and `baseUrl` explicitly. ### Per-request options [#per-request-options] Every method takes request options as its last argument: `{ timeoutMs, maxRetries, signal, headers }`. They override the client's settings for that call: ```ts const document = await druckling.documents.get("pdf_8Qw2kLm3nP0aB1cD", { timeoutMs: 5_000, maxRetries: 0 }); ``` `druckling.withOptions(options)` returns a copy of the client with some options changed, for example a longer timeout for large reports: ```ts const patient = druckling.withOptions({ timeoutMs: 180_000 }); ``` `druckling.mode` is `"test"` for `dr_test_…` keys and `"live"` otherwise. `druckling.baseUrl` is the origin requests go to, without `/v1`. ### Custom fetch [#custom-fetch] Pass `fetch` to route requests through your own implementation, for example to add metrics or tracing. It receives the same arguments as the global `fetch`, including the requests to signed download URLs: ```ts const druckling = new Druckling({ fetch: async (input, init) => { const started = Date.now(); const response = await fetch(input, init); metrics.timing("druckling.request", Date.now() - started, { status: String(response.status) }); return response; }, }); ``` ## Render a document [#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 resolves with a `rendered` document: ```ts import { writeFile } from "node:fs/promises"; import Druckling from "@druckling/sdk"; const druckling = new Druckling(); const 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" }, }; const document = await druckling.documents.create({ template: "invoice-standard", filename: "INV-2041.pdf", data: invoice, }); console.log(document.id, document.status, document.pages); // pdf_… rendered 1 await writeFile("INV-2041.pdf", await druckling.documents.download(document)); ``` The parameters are `template` (slug), `data`, and optionally `version` (a published version number, default `"latest"`), `filename`, `async`, `language` and `format`. The returned `Document` uses the API's field names (`size_bytes`, `content_type`, `created_at`, …), so it matches the [API reference](/docs/api-reference/documents/create) and webhook payloads one to one. `data` must match the template's schema. `(await druckling.templates.get("invoice-standard")).sample_data` is a payload that renders. See [Variables](/docs/concepts/variables). ## Render asynchronously and wait [#render-asynchronously-and-wait] Pass `async: true` to queue the render. `create` resolves 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](#webhooks): ```ts import { DocumentFailedError, WaitTimeoutError } from "@druckling/sdk"; const queued = await druckling.documents.create({ template: "invoice-standard", data: invoice, async: true }); console.log(queued.status); // queued try { const document = await druckling.documents.wait(queued, { timeoutMs: 120_000, intervalMs: 1_000 }); const pdf = await druckling.documents.download(document); } catch (error) { if (error instanceof DocumentFailedError) { console.error(error.document.error?.message); } else if (error instanceof WaitTimeoutError) { console.warn(`still ${error.document.status}, check again later`); } else { throw error; } } ``` `wait(document, options?)` accepts a `Document` or a document ID and polls `documents.get`: | Option | Default | Notes | | --- | --- | --- | | `timeoutMs` | `120000` | Overall time to wait. | | `intervalMs` | `1000` | Time between polls. | | `signal` | none | An `AbortSignal` that stops waiting. | It resolves with the document once it's `rendered`. It throws `DocumentFailedError` when the document ends `failed` or `expired` (`error.document` holds it), and `WaitTimeoutError` when the next poll would pass the timeout (`error.document` is the last state seen). Each poll is an API request and counts toward your key's rate limit. ## Download the file [#download-the-file] `documents.download(document, options?)` resolves with the file as a `Uint8Array`: a PDF, a PNG or an XML e-invoice, depending on the document's `format`. It fetches the file from the document's signed `url`; your API key isn't sent there. ```ts const bytes = await druckling.documents.download(document); await writeFile(document.filename, bytes); ``` - Pass a document ID instead of a `Document` to 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 at `expires_at`. - A document that is `failed` or `expired` throws `DocumentFailedError`. One that is still `queued` or `rendering` throws a `DrucklingError`; call `wait` first. - A failed request to the signed URL throws an `APIError` with `code: "download_failed"`. ## PNG and XML output [#png-and-xml-output] Pass `format: "png"` to render the first page as a PNG at 144 dpi instead of a PDF: ```ts const preview = await druckling.documents.create({ template: "invoice-standard", data: invoice, format: "png" }); console.log(preview.content_type, preview.pages); // image/png 1 await writeFile("INV-2041.png", await druckling.documents.download(preview)); ``` 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), and the `Document` type doesn't declare the `image` field. To use them, call the API directly and hand the result to the SDK's helpers: ```ts import type { Document } from "@druckling/sdk"; const response = await fetch("https://druckling-nine.vercel.app/v1/documents", { method: "POST", headers: { authorization: `Bearer ${process.env.DRUCKLING_API_KEY}`, "content-type": "application/json" }, body: JSON.stringify({ template: "invoice-standard", data: invoice, format: "png", image: { page: 1, scale: 4 } }), }); if (!response.ok) throw new Error(`Render failed with HTTP ${response.status}: ${await response.text()}`); const hiRes = (await response.json()) as Document; await writeFile("INV-2041@4x.png", await druckling.documents.download(hiRes)); ``` 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 throws a `ValidationError` with `field: "format"`. See [PNG output](/docs/guides/png-output) and [E-invoicing](/docs/guides/e-invoicing). ## Languages [#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: ```ts const template = await druckling.templates.get("invoice-standard"); console.log(template.language, template.languages); // en ["en", "de"], default first const rechnung = await druckling.documents.create({ template: "invoice-standard", language: "de", filename: "RE-2041.pdf", data: invoice, }); console.log(rechnung.language); // de ``` Without `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 throws a `ValidationError` with `field: "language"`. See [Languages](/docs/guides/languages). ## List documents [#list-documents] `documents.list(params?)` returns documents newest first. Await it for one page, or iterate it with `for await` to walk every matching document; the SDK fetches the following pages as you go: ```ts for await (const document of druckling.documents.list({ status: "failed", template: "invoice-standard" })) { console.log(document.id, document.created_at, document.error?.message); } const page = await druckling.documents.list({ limit: 20 }); page.data; // up to 20 documents page.next_cursor; // pass as `cursor` to resume later, or null page.hasNextPage(); // boolean await page.getNextPage(); // the next CursorPage, or null ``` Filters: `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](/docs/api-reference/documents/list). ## Templates [#templates] ```ts const { data: templates } = await druckling.templates.list(); for (const template of templates) { console.log(template.slug, template.status, template.latest_version, template.required_fields); } const template = await druckling.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 a `PermissionDeniedError`. - `templates.list()` resolves with `{ object: "list", data }` holding every template of the workspace, drafts included. It isn't paginated. See [List templates](/docs/api-reference/templates/list) and [Retrieve a template](/docs/api-reference/templates/get). - `json_schema`, `sample_data`, `required_fields` and `languages` come 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 [#errors] Every error the SDK throws extends `DrucklingError`. Errors from the API are `APIError` subclasses: ```text DrucklingError ├── APIError │ ├── ValidationError │ ├── AuthenticationError │ ├── PermissionDeniedError │ ├── NotFoundError │ ├── ConflictError │ ├── RenderError │ ├── RateLimitError │ │ └── QuotaExceededError │ └── ServerError ├── APIConnectionError │ └── APITimeoutError ├── DocumentFailedError ├── WaitTimeoutError └── WebhookVerificationError ``` The class follows Druckling's error `code` first, then the HTTP status: | Error | 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 `download` found the document `failed` or `expired`. `error.document` holds it. | | `WaitTimeoutError` | `wait` ran out of time. `error.document` is the last state seen. | | `WebhookVerificationError` | A webhook's signature, timestamp or body didn't verify. | An `APIError` carries: | Property | Type | Notes | | --- | --- | --- | | `status` | `number` | HTTP status. | | `code` | `ErrorCode` | Druckling's error code, for example `schema_validation_failed`. See [Errors](/docs/concepts/errors). | | `message` | `string` | Human-readable description. | | `field` | `string` or `null` | Dotted path of the offending field, for example `customer.name` or `language`. | | `errors` | `FieldError[]` | Every offending field: `{ field, message, rule? }`. `rule` names a broken e-invoice business rule such as `BR-CO-25`. | | `documentId` | `string` or `null` | The failed document recorded for a payload that didn't validate. | | `retryAfter` | `number` or `null` | Seconds from the response's `Retry-After` header, when it has one. | | `requestId` | `string` or `null` | Quote it when you contact support. | | `headers` | `Headers` | Response headers. | | `body` | `unknown` | Parsed JSON body, or the raw text when it isn't JSON. | ```ts import { APIError, QuotaExceededError, RateLimitError, ValidationError } from "@druckling/sdk"; try { await druckling.documents.create({ template: "invoice-standard", data: { customer: {} } }); } catch (error) { if (error instanceof ValidationError) { console.log(error.message); // Required field invoice was missing from the request payload console.log(error.documentId); // pdf_… (the failed document is kept for your logs) for (const { field, message } of error.errors) console.log(field, "→", 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 } else if (error instanceof QuotaExceededError) { notifyBilling(error.message); } else if (error instanceof RateLimitError) { requeueLater(); } else if (error instanceof APIError) { console.error(error.status, error.code, error.message, error.requestId); } else { throw error; } } ``` Check `QuotaExceededError` before `RateLimitError`, since it's a subclass. ## Retries and timeouts [#retries-and-timeouts] The client retries failed requests up to `maxRetries` times (default 2): - `429 rate_limited` is retried for every request, including renders: a rate-limited request produced no file. - `429 quota_exceeded` is never retried; you get a `QuotaExceededError` right away. - `408`, `5xx`, timeouts and connection errors are retried for `GET` and `DELETE` requests only, including downloads from signed URLs. - `POST` requests (`documents.create`, `webhookEndpoints.create`, `embedSessions.create`) aren't retried after a `5xx`, 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. Catch `ServerError` and `APIConnectionError` and 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 thrown to you without retrying. `timeoutMs` (default 60 seconds) limits each attempt, including reading the response. Synchronous renders happen inside the request, so leave room for large documents, or render them with `async: true`. When you abort a request with your own `signal`, the SDK rethrows the signal's reason instead of an `APITimeoutError`, and doesn't retry. ## Webhooks [#webhooks] Druckling can call your HTTPS endpoint when a document is rendered, fails or expires. Deliveries follow the [Standard Webhooks](https://www.standardwebhooks.com/) spec: `webhook-id`, `webhook-timestamp` and `webhook-signature` headers, signed with HMAC-SHA256 over the raw body. ### Verify signatures [#verify-signatures] `verifyWebhook(payload, headers, secret, options?)` checks the signature and the timestamp, then resolves with the typed event. Pass the **raw** body, before any JSON parsing; re-serialized JSON won't match the signature. ```ts title="app/api/webhooks/druckling/route.ts" import { verifyWebhook, WebhookVerificationError } from "@druckling/sdk"; export async function POST(request: Request) { let event; try { event = await verifyWebhook(await request.text(), request.headers, process.env.DRUCKLING_WEBHOOK_SECRET!); } catch (error) { if (error instanceof WebhookVerificationError) return new Response(null, { status: 400 }); throw error; } if (event.type === "document.rendered") { await saveInvoice(event.data.id, event.data.url); } return new Response(null, { status: 204 }); } ``` With Express, use `express.raw()` on the webhook route so the body stays a `Buffer`: ```ts title="server.ts" import express from "express"; import { verifyWebhook, WebhookVerificationError } from "@druckling/sdk"; const app = express(); app.post("/webhooks/druckling", express.raw({ type: "application/json" }), async (req, res) => { try { const event = await verifyWebhook(req.body, req.headers, process.env.DRUCKLING_WEBHOOK_SECRET!); if (event.type === "document.failed") await alertOps(event.data.error?.message); res.sendStatus(204); } catch (error) { if (error instanceof WebhookVerificationError) return res.sendStatus(400); throw error; } }); ``` | Parameter | Type | Notes | | --- | --- | --- | | `payload` | `string`, `Uint8Array` (or `Buffer`), `ArrayBuffer` | The raw request body. | | `headers` | `Headers`, or a plain object such as Node's `req.headers` | Header names are matched case-insensitively. | | `secret` | `string` | The endpoint's `whsec_…` signing secret. | | `options.toleranceSeconds` | `number` | Maximum age and clock skew of `webhook-timestamp`. Default `300`. | | `options.now` | `Date` | Override the current time, for tests. | The event is `{ id, object: "event", type, created_at, test_mode, data }`. For `document.rendered`, `document.failed` and `document.expired`, `data` is a `Document`, and checking `event.type` narrows it. - **Duplicates**: a delivery can arrive more than once. Use `event.id` (the same as the `webhook-id` header) to ignore repeats; a resent event keeps its ID. - **Answer fast**: respond with a `2xx` within 10 seconds and do slow work in a queue. Other answers and timeouts are retried for about 8.6 hours. Don't answer `410 Gone` unless 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.ping` event; `data` is `{ object: "ping", endpoint_id, message }`. - **Batches**: `batch.completed` events verify like any other, but the SDK's event types don't include them yet. Compare `event.type as string` against `"batch.completed"` and treat `event.data` as the batch. `verifyWebhookSignature(payload, headers, secret, options?)` checks the signature without parsing the body. To test your handler, `await signWebhook(secret, id, timestamp, body)` returns a valid `webhook-signature` value (`timestamp` in Unix seconds or a `Date`). ### Manage webhook endpoints [#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. ```ts const endpoint = await druckling.webhookEndpoints.create({ url: "https://example.com/webhooks/druckling", events: ["document.rendered", "document.failed"], description: "Invoice mailer", }); console.log(endpoint.id, endpoint.secret); // whe_… whsec_… const { data: endpoints } = await druckling.webhookEndpoints.list(); await druckling.webhookEndpoints.get(endpoint.id); await druckling.webhookEndpoints.delete(endpoint.id); // { id, object: "webhook_endpoint", deleted: true } ``` The `secret` is returned only by `create`: store it now. The URL must be a public `https://` URL. See [Webhooks](/docs/guides/webhooks) for the event payloads and delivery details, and the [webhook endpoint reference](/docs/api-reference/webhooks/create) for every field. ## Embedded editor sessions [#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: ```ts title="app/api/template-editor/route.ts" import Druckling from "@druckling/sdk"; const druckling = new Druckling(); export async function POST(request: Request) { const user = await requireUser(request); // your own authentication const session = await druckling.embedSessions.create({ template: "invoice-standard", permissions: { publish: true }, user: { id: user.id, name: user.name }, theme: { mode: "system", accent: "#0f766e" }, expiresIn: 1800, }); return Response.json({ url: session.url }, { headers: { "cache-control": "no-store" } }); } ``` | Parameter | Default | Notes | | --- | --- | --- | | `template` | required | Slug of the template to edit. | | `permissions.publish` | `false` | Let the user publish new versions. By default they edit the draft and you publish. | | `permissions.assistant` | `false` | Offer the AI assistant, on plans that include it. The returned `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. | | `expiresIn` | `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](/docs/guides/embedded-editor), and the reference for [creating](/docs/api-reference/embedded-editor/create) and [revoking](/docs/api-reference/embedded-editor/revoke) sessions. - The `url` carries the session token in its fragment (`#token=…`). Give it only to the signed-in user's browser; never log, cache or store it. Only `create` returns it. - `druckling.embedSessions.revoke(session.id)` ends a session right away, for example when the user signs out. It resolves with the session, now `status: "revoked"` and `url: null`. Revoking twice is fine. - `create` throws `ConflictError` (`invalid_state`) until an origin is allowed in **Settings › Embed**, `PermissionDeniedError` for a Render only key, `ValidationError` for bad options, and `RateLimitError` beyond about 60 sessions a minute per workspace. ## Test and live keys [#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 carries `test_mode: true`. - `dr_live_…` keys are for production. Live renders count toward your plan's quota. `druckling.mode` tells you which one a client uses. See [Test mode](/docs/concepts/test-mode). ## Next steps [#next-steps] Every endpoint, field and error of the REST API the SDK wraps. Event payloads, delivery retries and secret rotation. What each error code means and how to handle it. # API reference (/docs/api-reference) > Conventions of the Druckling REST API, and a reference for every endpoint generated from the API's own contract. The Druckling API is a JSON REST API. Every endpoint in this section is generated from the same contract the API is served from, so field names, types and limits here always match what `/v1` accepts. Use the playground on each page to send a request with your test key. ## Base URL [#base-url] ```text https://druckling-nine.vercel.app/v1 ``` All endpoints are versioned under `/v1`. Requests and responses use JSON (`Content-Type: application/json`) with `snake_case` field names, and timestamps are ISO 8601 strings in UTC. ## Authentication [#authentication] Send an API key with every request, either as a bearer token or in the `x-api-key` header: ```bash tab="Bearer" curl https://druckling-nine.vercel.app/v1/templates \ -H "Authorization: Bearer $DRUCKLING_API_KEY" ``` ```bash tab="x-api-key" curl https://druckling-nine.vercel.app/v1/templates \ -H "x-api-key: $DRUCKLING_API_KEY" ``` The key decides the workspace and the mode: `dr_test_…` keys work in [test mode](/docs/concepts/test-mode), `dr_live_…` keys in live mode. Some endpoints need a key with full access. See [Authentication](/docs/authentication) for permissions and the errors you get without them. ## Resources and IDs [#resources-and-ids] Every resource has an `object` field naming its type and an `id` with a prefix you can recognize: | Resource | `object` | ID prefix | | --- | --- | --- | | [Document](/docs/api-reference/documents/get) | `document` | `pdf_` | | [Batch](/docs/api-reference/batches/get) | `batch` | `bat_` | | [Share link](/docs/api-reference/share-links/create) | `share_link` | `shl_` | | [Webhook endpoint](/docs/api-reference/webhooks/get) | `webhook_endpoint` | `whe_` | | [Embedded editor session](/docs/api-reference/embedded-editor/create) | `embed_session` | `emb_` | | [Template](/docs/api-reference/templates/get) | `template` | addressed by its `slug` | ## Lists and pagination [#lists-and-pagination] List endpoints return `{ "object": "list", "data": [...] }`. Documents, batches and a batch's documents are paginated: pass `limit` (1 to 100) and, for the next page, `cursor` set to the previous response's `next_cursor`. `next_cursor` is `null` on the last page. Templates, webhook endpoints and share links come back in one list. The [SDKs](/docs/sdks) iterate through pages for you. ## Status codes [#status-codes] | Status | Meaning | | --- | --- | | `200` | It worked. `POST /v1/documents` answers `200` when it waited for the render. | | `201` | A webhook endpoint, share link or embedded editor session was created. | | `202` | Accepted and queued: `POST /v1/documents` with `async: true`, and every batch. | | `400` | The request doesn't match the API's schema (`data.issues` lists the problems). | | `401` / `403` | The API key is missing or invalid, or lacks a permission. | | `404` | The resource doesn't exist in your workspace, or the endpoint doesn't exist. | | `409` | The request conflicts with the resource's state, e.g. canceling a finished batch. | | `413` | The request body is too large. | | `422` | The payload doesn't match the template's schema, a business rule failed, or the render failed. | | `429` | A quota or rate limit was reached. | | `504` | The render took too long. | Every error has the same JSON shape, with Druckling's own code in `data.code` and the offending field in `data.field`. See [Errors](/docs/concepts/errors) for the full list and for which errors are safe to retry, and [Plans and limits](/docs/concepts/plans-and-limits) for quotas and rate limits. ## OpenAPI [#openapi] The OpenAPI 3.1 document behind this reference is served at [`/v1/openapi.json`](/v1/openapi.json). Use it to generate a client in another language or to import the API into a tool such as Postman or Insomnia. An interactive Scalar reference is also available at [`/v1/docs`](/v1/docs). # Send an event (/docs/api-reference/events/send) > Starts every enabled workflow listening to type in the API key's mode (Workflows page): each renders its template from data, then signs, stores, emails or calls a URL as configured. `POST https://druckling-nine.vercel.app/v1/events` Starts every enabled workflow listening to `type` in the API key's mode (Workflows page): each renders its template from `data`, then signs, stores, emails or calls a URL as configured. Runs happen in the background; follow them on the Workflows page or with the `workflow.run_succeeded` / `workflow.run_failed` webhooks. Send an `idempotency_key` (e.g. your order id) to make retries safe: an event with a key already seen in the last 30 days returns the original event with `duplicate: true` and starts nothing. Event payloads are kept 30 days. Needs a key with `documents:create`; `data` up to 256 KB. ## Request body (JSON Schema) ```json { "type": "object", "properties": { "type": { "type": "string", "minLength": 1, "maxLength": 100, "description": "Event name: letters, digits and `. _ : -`." }, "data": { "type": "object", "propertyNames": { "type": "string" }, "additionalProperties": {}, "description": "The payload workflows render from (default `{}`)." }, "idempotency_key": { "type": "string", "maxLength": 255 } }, "required": [ "type" ] } ``` ## Response 202: OK ```json { "type": "object", "properties": { "id": { "type": "string" }, "object": { "const": "event" }, "type": { "type": "string" }, "idempotency_key": { "anyOf": [ { "type": "string" }, { "type": "null" } ] }, "duplicate": { "type": "boolean", "description": "True when an event with the same `idempotency_key` was already received: this is that event, and nothing new ran." }, "runs": { "type": "array", "items": { "type": "object", "properties": { "id": { "type": "string" }, "workflow": { "type": "object", "properties": { "id": { "type": "string" }, "name": { "type": "string" } }, "required": [ "id", "name" ] }, "status": { "enum": [ "queued", "running", "waiting", "succeeded", "failed" ], "type": "string", "description": "`waiting`: a dataset's batches are rendering. `succeeded` and `failed` are final." } }, "required": [ "id", "workflow", "status" ] }, "description": "The workflow runs the event started, one per enabled workflow of the key's mode listening to `type`." }, "test_mode": { "type": "boolean" }, "created_at": { "type": "string", "format": "date-time" } }, "required": [ "id", "object", "type", "idempotency_key", "duplicate", "runs", "test_mode", "created_at" ] } ``` # Create an embedded editor session (/docs/api-reference/embedded-editor/create) > Lets one of your users edit one template inside your product, in Druckling's white-label editor. `POST https://druckling-nine.vercel.app/v1/embed_sessions` Lets one of your users edit one template inside your product, in Druckling's white-label editor. Call this from your backend with a full-access key (`templates:write`) when the user opens the editor, then give the returned `url` to their browser. The editor loads in an iframe on the origins allowed in Settings › Embed (enforced with CSP `frame-ancestors`); without any allowed origin the answer is 409 `invalid_state`. The session can read that template, save its draft, render previews and, if you allow it, publish. Nothing else in the workspace (other templates, documents, API keys, webhooks, billing, team) is reachable with it. Sessions are short-lived: 30 minutes by default, at most an hour. When one expires the editor tells your page with an `error` event (`session_expired`); create a new session to continue. Drafts are saved continuously, so nothing is lost. The editor shows a small "Powered by Druckling" mark on the Free and Starter plans. ## Request body (JSON Schema) ```json { "type": "object", "properties": { "template": { "type": "string", "minLength": 1, "maxLength": 64, "description": "Slug of the template to edit, e.g. invoice-standard." }, "permissions": { "type": "object", "properties": { "publish": { "type": "boolean", "description": "Let the user publish new versions (default false: the user edits the draft, you publish)." }, "assistant": { "type": "boolean", "description": "Offer the AI assistant, on plans that include it (Pro, Business). Default false." } } }, "expires_in": { "type": "integer", "minimum": 60, "maximum": 3600, "description": "Seconds until the session ends: default 1800, at most 3600." }, "user": { "type": "object", "properties": { "id": { "type": "string", "minLength": 1, "maxLength": 200, "description": "Your id for the user." }, "name": { "type": "string", "maxLength": 200 } }, "required": [ "id" ], "description": "Who is editing. Shown in Druckling's request logs and on the versions they publish (`embed:`)." }, "theme": { "type": "object", "properties": { "mode": { "enum": [ "light", "dark", "system" ], "type": "string", "description": "Default `light`. `system` follows the user's OS setting." }, "accent": { "type": "string", "pattern": "^#(?:[0-9a-fA-F]{3}){1,2}$", "description": "Your brand color for buttons and highlights, e.g. `#0f766e`." } } } }, "required": [ "template" ] } ``` ## Response 201: OK ```json { "type": "object", "properties": { "id": { "type": "string" }, "object": { "const": "embed_session" }, "url": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "Load this URL in an iframe (or pass it to `mountEditor` from `@druckling/embed`). Returned only when the session is created. The session token sits in the fragment (`#token=…`), which browsers never send to servers; Druckling keeps only a hash of it. Hand the URL to the signed-in user's browser only, never log or cache it." }, "template": { "type": "string", "description": "Slug of the template the session edits." }, "permissions": { "type": "object", "properties": { "publish": { "type": "boolean", "description": "The user can publish new versions." }, "assistant": { "type": "boolean", "description": "The AI assistant is offered. False when the plan doesn't include it, even if you asked for it." } }, "required": [ "publish", "assistant" ], "description": "What the editor offers beyond editing the draft." }, "user": { "anyOf": [ { "type": "object", "properties": { "id": { "type": "string" }, "name": { "anyOf": [ { "type": "string" }, { "type": "null" } ] } }, "required": [ "id", "name" ] }, { "type": "null" } ], "description": "Your user, as you described them." }, "theme": { "type": "object", "properties": { "mode": { "enum": [ "light", "dark", "system" ], "type": "string" }, "accent": { "anyOf": [ { "type": "string" }, { "type": "null" } ] } }, "required": [ "mode", "accent" ] }, "status": { "enum": [ "active", "expired", "revoked" ], "type": "string" }, "expires_at": { "type": "string", "format": "date-time" }, "revoked_at": { "anyOf": [ { "type": "string", "format": "date-time" }, { "type": "null" } ] }, "test_mode": { "type": "boolean" }, "created_at": { "type": "string", "format": "date-time" } }, "required": [ "id", "object", "url", "template", "permissions", "user", "theme", "status", "expires_at", "revoked_at", "test_mode", "created_at" ] } ``` # Revoke an embedded editor session (/docs/api-reference/embedded-editor/revoke) > Ends the session right away, e.g. `DELETE https://druckling-nine.vercel.app/v1/embed_sessions/{id}` Ends the session right away, e.g. when the user signs out of your product. The open editor reports `session_revoked` on its next request. Revoking twice is fine. ## Parameters | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `id` | path | string | yes | | ## Response 200: OK ```json { "type": "object", "properties": { "id": { "type": "string" }, "object": { "const": "embed_session" }, "url": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "Load this URL in an iframe (or pass it to `mountEditor` from `@druckling/embed`). Returned only when the session is created. The session token sits in the fragment (`#token=…`), which browsers never send to servers; Druckling keeps only a hash of it. Hand the URL to the signed-in user's browser only, never log or cache it." }, "template": { "type": "string", "description": "Slug of the template the session edits." }, "permissions": { "type": "object", "properties": { "publish": { "type": "boolean", "description": "The user can publish new versions." }, "assistant": { "type": "boolean", "description": "The AI assistant is offered. False when the plan doesn't include it, even if you asked for it." } }, "required": [ "publish", "assistant" ], "description": "What the editor offers beyond editing the draft." }, "user": { "anyOf": [ { "type": "object", "properties": { "id": { "type": "string" }, "name": { "anyOf": [ { "type": "string" }, { "type": "null" } ] } }, "required": [ "id", "name" ] }, { "type": "null" } ], "description": "Your user, as you described them." }, "theme": { "type": "object", "properties": { "mode": { "enum": [ "light", "dark", "system" ], "type": "string" }, "accent": { "anyOf": [ { "type": "string" }, { "type": "null" } ] } }, "required": [ "mode", "accent" ] }, "status": { "enum": [ "active", "expired", "revoked" ], "type": "string" }, "expires_at": { "type": "string", "format": "date-time" }, "revoked_at": { "anyOf": [ { "type": "string", "format": "date-time" }, { "type": "null" } ] }, "test_mode": { "type": "boolean" }, "created_at": { "type": "string", "format": "date-time" } }, "required": [ "id", "object", "url", "template", "permissions", "user", "theme", "status", "expires_at", "revoked_at", "test_mode", "created_at" ] } ``` # List webhook endpoints (/docs/api-reference/webhooks/list) `GET https://druckling-nine.vercel.app/v1/webhook_endpoints` ## Response 200: OK ```json { "type": "object", "properties": { "object": { "const": "list" }, "data": { "type": "array", "items": { "type": "object", "properties": { "id": { "type": "string" }, "object": { "const": "webhook_endpoint" }, "url": { "type": "string" }, "description": { "type": "string" }, "events": { "type": "array", "items": { "enum": [ "document.rendered", "document.failed", "document.expired", "batch.completed", "document.delivered", "document.delivery_failed", "workflow.run_succeeded", "workflow.run_failed" ], "type": "string", "description": "`batch.completed` is sent once per batch when it reaches a final status (`completed`, `failed` or `canceled`); `data` is the batch. `document.delivered` and `document.delivery_failed` follow a document's copy to your own bucket (`data.storage`); a failure is sent once retries are used up. `workflow.run_succeeded` and `workflow.run_failed` are sent when a workflow run finishes; `data` is the run with each step's outcome." } }, "enabled": { "type": "boolean" }, "test_mode": { "type": "boolean" }, "created_at": { "type": "string", "format": "date-time" } }, "required": [ "id", "object", "url", "description", "events", "enabled", "test_mode", "created_at" ] } } }, "required": [ "object", "data" ] } ``` # Create a webhook endpoint (/docs/api-reference/webhooks/create) > Subscribes an HTTPS URL to document events in the API key's mode. `POST https://druckling-nine.vercel.app/v1/webhook_endpoints` Subscribes an HTTPS URL to document events in the API key's mode. The signing `secret` is returned only here. Requests follow the Standard Webhooks spec (`webhook-id`, `webhook-timestamp`, `webhook-signature`). Needs a full-access key. ## Request body (JSON Schema) ```json { "type": "object", "properties": { "url": { "type": "string", "maxLength": 2048, "description": "Public https:// URL that answers 2xx within 10 seconds." }, "events": { "type": "array", "minItems": 1, "items": { "enum": [ "document.rendered", "document.failed", "document.expired", "batch.completed", "document.delivered", "document.delivery_failed", "workflow.run_succeeded", "workflow.run_failed" ], "type": "string", "description": "`batch.completed` is sent once per batch when it reaches a final status (`completed`, `failed` or `canceled`); `data` is the batch. `document.delivered` and `document.delivery_failed` follow a document's copy to your own bucket (`data.storage`); a failure is sent once retries are used up. `workflow.run_succeeded` and `workflow.run_failed` are sent when a workflow run finishes; `data` is the run with each step's outcome." } }, "description": { "type": "string", "maxLength": 200 } }, "required": [ "url", "events" ] } ``` ## Response 201: OK ```json { "type": "object", "properties": { "id": { "type": "string" }, "object": { "const": "webhook_endpoint" }, "url": { "type": "string" }, "description": { "type": "string" }, "events": { "type": "array", "items": { "enum": [ "document.rendered", "document.failed", "document.expired", "batch.completed", "document.delivered", "document.delivery_failed", "workflow.run_succeeded", "workflow.run_failed" ], "type": "string", "description": "`batch.completed` is sent once per batch when it reaches a final status (`completed`, `failed` or `canceled`); `data` is the batch. `document.delivered` and `document.delivery_failed` follow a document's copy to your own bucket (`data.storage`); a failure is sent once retries are used up. `workflow.run_succeeded` and `workflow.run_failed` are sent when a workflow run finishes; `data` is the run with each step's outcome." } }, "enabled": { "type": "boolean" }, "test_mode": { "type": "boolean" }, "created_at": { "type": "string", "format": "date-time" }, "secret": { "type": "string", "description": "whsec_… signing secret; store it now." } }, "required": [ "id", "object", "url", "description", "events", "enabled", "test_mode", "created_at", "secret" ] } ``` # Retrieve a webhook endpoint (/docs/api-reference/webhooks/get) `GET https://druckling-nine.vercel.app/v1/webhook_endpoints/{id}` ## Parameters | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `id` | path | string | yes | | ## Response 200: OK ```json { "type": "object", "properties": { "id": { "type": "string" }, "object": { "const": "webhook_endpoint" }, "url": { "type": "string" }, "description": { "type": "string" }, "events": { "type": "array", "items": { "enum": [ "document.rendered", "document.failed", "document.expired", "batch.completed", "document.delivered", "document.delivery_failed", "workflow.run_succeeded", "workflow.run_failed" ], "type": "string", "description": "`batch.completed` is sent once per batch when it reaches a final status (`completed`, `failed` or `canceled`); `data` is the batch. `document.delivered` and `document.delivery_failed` follow a document's copy to your own bucket (`data.storage`); a failure is sent once retries are used up. `workflow.run_succeeded` and `workflow.run_failed` are sent when a workflow run finishes; `data` is the run with each step's outcome." } }, "enabled": { "type": "boolean" }, "test_mode": { "type": "boolean" }, "created_at": { "type": "string", "format": "date-time" } }, "required": [ "id", "object", "url", "description", "events", "enabled", "test_mode", "created_at" ] } ``` # Delete a webhook endpoint (/docs/api-reference/webhooks/delete) `DELETE https://druckling-nine.vercel.app/v1/webhook_endpoints/{id}` ## Parameters | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `id` | path | string | yes | | ## Response 200: OK ```json { "type": "object", "properties": { "id": { "type": "string" }, "object": { "const": "webhook_endpoint" }, "deleted": { "const": true } }, "required": [ "id", "object", "deleted" ] } ``` # List documents (/docs/api-reference/documents/list) `GET https://druckling-nine.vercel.app/v1/documents` ## Parameters | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `limit` | query | integer | no | | | `cursor` | query | string | no | | | `status` | query | string | no | | | `template` | query | string | no | | ## Response 200: OK ```json { "type": "object", "properties": { "object": { "const": "list" }, "data": { "type": "array", "items": { "type": "object", "properties": { "id": { "type": "string" }, "object": { "const": "document" }, "status": { "enum": [ "queued", "rendering", "rendered", "failed", "expired" ], "type": "string" }, "template": { "type": "string" }, "version": { "anyOf": [ { "type": "number" }, { "type": "null" } ] }, "filename": { "type": "string" }, "format": { "enum": [ "pdf", "png", "xml" ], "type": "string", "description": "`xml` for XRechnung and Peppol BIS e-invoices." }, "content_type": { "type": "string", "description": "`application/pdf`, `image/png` or `application/xml`." }, "image": { "anyOf": [ { "type": "object", "properties": { "page": { "type": "number", "description": "The page that was rendered (1-based)." }, "scale": { "type": "number", "description": "Pixels per point: 2 = 144 dpi." }, "width": { "anyOf": [ { "type": "number" }, { "type": "null" } ], "description": "Pixel width, once rendered." }, "height": { "anyOf": [ { "type": "number" }, { "type": "null" } ], "description": "Pixel height, once rendered." } }, "required": [ "page", "scale", "width", "height" ] }, { "type": "null" } ], "description": "Set for `png` documents." }, "pages": { "anyOf": [ { "type": "number" }, { "type": "null" } ], "description": "Pages in the file (a PNG is one page; null for XML)." }, "size_bytes": { "anyOf": [ { "type": "number" }, { "type": "null" } ] }, "url": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "Signed download URL while the document is retained." }, "expires_at": { "anyOf": [ { "type": "string", "format": "date-time" }, { "type": "null" } ] }, "error": { "anyOf": [ { "type": "object", "properties": { "code": { "type": "string" }, "message": { "type": "string" }, "field": { "anyOf": [ { "type": "string" }, { "type": "null" } ] } }, "required": [ "code", "message", "field" ] }, { "type": "null" } ] }, "einvoice": { "anyOf": [ { "type": "object", "properties": { "format": { "enum": [ "factur-x", "xrechnung", "peppol" ], "type": "string", "description": "`factur-x`: Factur-X 1.0 / ZUGFeRD 2.x hybrid invoice, a PDF/A-3 with the CII XML embedded. `xrechnung`: XRechnung 3.0 (German CIUS) as XML. `peppol`: Peppol BIS Billing 3.0 as UBL XML." }, "syntax": { "enum": [ "cii", "ubl" ], "type": "string", "description": "XML syntax: UN/CEFACT CII (Factur-X, XRechnung on request) or OASIS UBL 2.1 (XRechnung default, Peppol)." }, "profile": { "type": "string", "description": "`EN 16931`, `XRechnung 3.0` or `Peppol BIS Billing 3.0`." }, "customization_id": { "type": "string", "description": "Specification identifier (BT-24) written into the XML." }, "attachment": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "File name of the XML embedded in the PDF; null when the document is the XML itself." } }, "required": [ "format", "syntax", "profile", "customization_id", "attachment" ] }, { "type": "null" } ], "description": "Set when the document is or carries an e-invoice (templates with e-invoicing on)." }, "batch": { "anyOf": [ { "type": "object", "properties": { "id": { "type": "string" }, "index": { "type": "number", "description": "Position of the item in the batch's `items`." } }, "required": [ "id", "index" ] }, { "type": "null" } ], "description": "Set for documents rendered as part of a batch." }, "language": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "Language the document was rendered in (one of the template's `languages`); null for documents rendered before templates had languages." }, "signature": { "anyOf": [ { "type": "object", "properties": { "certificate": { "type": "string", "description": "Id of the workspace certificate that signed the PDF." }, "certificate_name": { "type": "string" }, "subject": { "type": "string", "description": "The signer, from the certificate." }, "level": { "enum": [ "B-B", "B-T" ], "type": "string", "description": "PAdES baseline level (ETSI EN 319 142-1): `B-T` carries a trusted timestamp from a timestamp authority, `B-B` does not." }, "signed_at": { "type": "string", "format": "date-time" }, "test_certificate": { "type": "boolean", "description": "Signed with a Druckling test certificate, which proves nothing about the signer." } }, "required": [ "certificate", "certificate_name", "subject", "level", "signed_at", "test_certificate" ] }, { "type": "null" } ], "description": "Set when the PDF carries a digital signature (PAdES) applied by Druckling." }, "storage": { "anyOf": [ { "type": "object", "properties": { "bucket": { "type": "string", "description": "Id of the bucket connection (Storage page)." }, "status": { "enum": [ "pending", "delivered", "failed" ], "type": "string", "description": "`pending` until the file is uploaded (retried with backoff for about 2.5 hours), then `delivered` or `failed`." }, "key": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "Object key in your bucket, from the bucket's path template." }, "error": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "What the bucket answered on the last failed attempt, e.g. `403 AccessDenied: Access Denied`." }, "attempts": { "type": "number" }, "delivered_at": { "anyOf": [ { "type": "string", "format": "date-time" }, { "type": "null" } ] } }, "required": [ "bucket", "status", "key", "error", "attempts", "delivered_at" ] }, { "type": "null" } ], "description": "Set when the document is also copied to your own S3-compatible bucket (request `storage`, or the template's bucket rule)." }, "test_mode": { "type": "boolean" }, "created_at": { "type": "string", "format": "date-time" } }, "required": [ "id", "object", "status", "template", "version", "filename", "format", "content_type", "image", "pages", "size_bytes", "url", "expires_at", "error", "einvoice", "batch", "language", "signature", "storage", "test_mode", "created_at" ] } }, "next_cursor": { "anyOf": [ { "type": "string" }, { "type": "null" } ] } }, "required": [ "object", "data", "next_cursor" ] } ``` # Render a document (/docs/api-reference/documents/create) > Validates data against the template's schema and renders a PDF, or one page as a PNG with format: "png". `POST https://druckling-nine.vercel.app/v1/documents` Validates `data` against the template's schema and renders a PDF, or one page as a PNG with `format: "png"`. Answers 200 with the rendered document and its signed URL, or with `async: true` 202 with the queued document to poll or wait for by webhook. For e-invoice templates `data.invoice` is an EN 16931 invoice: Druckling computes the totals and VAT breakdown and produces the template's e-invoice format: Factur-X / ZUGFeRD (the CII XML embedded as `factur-x.xml` in a PDF/A-3), XRechnung 3.0 (UBL or CII XML) or Peppol BIS Billing 3.0 (UBL XML). XRechnung and Peppol templates produce `format: "xml"` documents (`application/xml`). A broken business rule answers 422 `validation_failed` with the offending `field`: EN 16931 (BR-xx), XRechnung (BR-DE-xx) or Peppol (PEPPOL-EN16931-xxx, PEPPOL-COMMON-xxx, DE-R-xxx between German parties). ## Request body (JSON Schema) ```json { "type": "object", "properties": { "template": { "type": "string", "description": "Template slug, e.g. invoice-standard" }, "version": { "anyOf": [ { "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991, "exclusiveMinimum": 0 }, { "const": "latest" } ], "description": "Pinned version or `latest` (default)." }, "filename": { "type": "string", "maxLength": 200 }, "data": { "type": "object", "propertyNames": { "type": "string" }, "additionalProperties": {}, "description": "Payload matching the template schema." }, "async": { "type": "boolean", "description": "Queue the render and return 202 immediately." }, "format": { "enum": [ "pdf", "png", "xml" ], "type": "string", "description": "Output format; the template decides the default (`xml` for XRechnung and Peppol BIS e-invoice templates, `pdf` otherwise). `png` renders one page as an image; a template's PDF/A or PDF/UA setting applies to PDFs only. Factur-X templates render to `pdf` only, XRechnung and Peppol templates to `xml` only, and `xml` needs one of those (422 on `format`)." }, "image": { "type": "object", "properties": { "page": { "type": "integer", "minimum": 1, "maximum": 9007199254740991, "description": "Page to render (default 1); 422 on `image.page` if the document is shorter." }, "scale": { "type": "number", "minimum": 0.5, "maximum": 4, "description": "Pixels per point (default 2 = 144 dpi; 1 = 72 dpi, 4 = 288 dpi)." } }, "description": "PNG options; only allowed with `format: \"png\"`." }, "language": { "type": "string", "maxLength": 35, "description": "Language to render: one of the template's `languages` (default: its default language). Texts without a translation fall back to the default language; numbers, dates, hyphenation and the PDF's language follow this one. A regional tag such as `de-AT` uses `de`. 422 `validation_failed` on this field for a language the template doesn't have." }, "storage": { "anyOf": [ { "type": "object", "properties": { "bucket": { "type": "string", "minLength": 1, "maxLength": 64, "description": "A bucket id from the Storage page, or `default` for the workspace's default bucket." } }, "required": [ "bucket" ] }, { "const": false } ], "description": "Also copy the file to one of your own S3-compatible buckets (AWS S3, Cloudflare R2, Google Cloud Storage, Scaleway, Hetzner, OVHcloud, IONOS, MinIO…). The upload runs after the render (and signing, so the bucket gets the signed PDF), so it never slows the response; follow it in the document's `storage` or with the `document.delivered` / `document.delivery_failed` webhooks. Without this field the template's bucket rule applies, if there is one; `false` skips it. 422 `validation_failed` on `storage.bucket` for an unknown or disabled bucket." }, "sign": { "anyOf": [ { "type": "boolean" }, { "type": "object", "properties": { "certificate": { "type": "string", "maxLength": 64, "description": "Id of a certificate from Settings › Signing (default: the workspace's default certificate)." } } } ], "description": "Digitally sign the PDF (PAdES, invisible signature) with a certificate uploaded in Settings › Signing: `true` uses the default certificate, `{ \"certificate\": \"crt_…\" }` picks one. Unset: as the template says (its \"Sign rendered PDFs\" setting); `false` skips signing even then. PDF only (422 on `sign` for other formats). Signing is an incremental update, so PDF/A-3 (Factur-X) and PDF/UA documents keep their conformance. 404 on `sign.certificate` for an unknown certificate; 422 `signing_failed` when the workspace has no certificate, it has expired, or it can't sign." } }, "required": [ "template", "data" ] } ``` ## Response 200: Rendered ```json { "type": "object", "properties": { "id": { "type": "string" }, "object": { "const": "document" }, "status": { "enum": [ "queued", "rendering", "rendered", "failed", "expired" ], "type": "string" }, "template": { "type": "string" }, "version": { "anyOf": [ { "type": "number" }, { "type": "null" } ] }, "filename": { "type": "string" }, "format": { "enum": [ "pdf", "png", "xml" ], "type": "string", "description": "`xml` for XRechnung and Peppol BIS e-invoices." }, "content_type": { "type": "string", "description": "`application/pdf`, `image/png` or `application/xml`." }, "image": { "anyOf": [ { "type": "object", "properties": { "page": { "type": "number", "description": "The page that was rendered (1-based)." }, "scale": { "type": "number", "description": "Pixels per point: 2 = 144 dpi." }, "width": { "anyOf": [ { "type": "number" }, { "type": "null" } ], "description": "Pixel width, once rendered." }, "height": { "anyOf": [ { "type": "number" }, { "type": "null" } ], "description": "Pixel height, once rendered." } }, "required": [ "page", "scale", "width", "height" ] }, { "type": "null" } ], "description": "Set for `png` documents." }, "pages": { "anyOf": [ { "type": "number" }, { "type": "null" } ], "description": "Pages in the file (a PNG is one page; null for XML)." }, "size_bytes": { "anyOf": [ { "type": "number" }, { "type": "null" } ] }, "url": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "Signed download URL while the document is retained." }, "expires_at": { "anyOf": [ { "type": "string", "format": "date-time" }, { "type": "null" } ] }, "error": { "anyOf": [ { "type": "object", "properties": { "code": { "type": "string" }, "message": { "type": "string" }, "field": { "anyOf": [ { "type": "string" }, { "type": "null" } ] } }, "required": [ "code", "message", "field" ] }, { "type": "null" } ] }, "einvoice": { "anyOf": [ { "type": "object", "properties": { "format": { "enum": [ "factur-x", "xrechnung", "peppol" ], "type": "string", "description": "`factur-x`: Factur-X 1.0 / ZUGFeRD 2.x hybrid invoice, a PDF/A-3 with the CII XML embedded. `xrechnung`: XRechnung 3.0 (German CIUS) as XML. `peppol`: Peppol BIS Billing 3.0 as UBL XML." }, "syntax": { "enum": [ "cii", "ubl" ], "type": "string", "description": "XML syntax: UN/CEFACT CII (Factur-X, XRechnung on request) or OASIS UBL 2.1 (XRechnung default, Peppol)." }, "profile": { "type": "string", "description": "`EN 16931`, `XRechnung 3.0` or `Peppol BIS Billing 3.0`." }, "customization_id": { "type": "string", "description": "Specification identifier (BT-24) written into the XML." }, "attachment": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "File name of the XML embedded in the PDF; null when the document is the XML itself." } }, "required": [ "format", "syntax", "profile", "customization_id", "attachment" ] }, { "type": "null" } ], "description": "Set when the document is or carries an e-invoice (templates with e-invoicing on)." }, "batch": { "anyOf": [ { "type": "object", "properties": { "id": { "type": "string" }, "index": { "type": "number", "description": "Position of the item in the batch's `items`." } }, "required": [ "id", "index" ] }, { "type": "null" } ], "description": "Set for documents rendered as part of a batch." }, "language": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "Language the document was rendered in (one of the template's `languages`); null for documents rendered before templates had languages." }, "signature": { "anyOf": [ { "type": "object", "properties": { "certificate": { "type": "string", "description": "Id of the workspace certificate that signed the PDF." }, "certificate_name": { "type": "string" }, "subject": { "type": "string", "description": "The signer, from the certificate." }, "level": { "enum": [ "B-B", "B-T" ], "type": "string", "description": "PAdES baseline level (ETSI EN 319 142-1): `B-T` carries a trusted timestamp from a timestamp authority, `B-B` does not." }, "signed_at": { "type": "string", "format": "date-time" }, "test_certificate": { "type": "boolean", "description": "Signed with a Druckling test certificate, which proves nothing about the signer." } }, "required": [ "certificate", "certificate_name", "subject", "level", "signed_at", "test_certificate" ] }, { "type": "null" } ], "description": "Set when the PDF carries a digital signature (PAdES) applied by Druckling." }, "storage": { "anyOf": [ { "type": "object", "properties": { "bucket": { "type": "string", "description": "Id of the bucket connection (Storage page)." }, "status": { "enum": [ "pending", "delivered", "failed" ], "type": "string", "description": "`pending` until the file is uploaded (retried with backoff for about 2.5 hours), then `delivered` or `failed`." }, "key": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "Object key in your bucket, from the bucket's path template." }, "error": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "What the bucket answered on the last failed attempt, e.g. `403 AccessDenied: Access Denied`." }, "attempts": { "type": "number" }, "delivered_at": { "anyOf": [ { "type": "string", "format": "date-time" }, { "type": "null" } ] } }, "required": [ "bucket", "status", "key", "error", "attempts", "delivered_at" ] }, { "type": "null" } ], "description": "Set when the document is also copied to your own S3-compatible bucket (request `storage`, or the template's bucket rule)." }, "test_mode": { "type": "boolean" }, "created_at": { "type": "string", "format": "date-time" } }, "required": [ "id", "object", "status", "template", "version", "filename", "format", "content_type", "image", "pages", "size_bytes", "url", "expires_at", "error", "einvoice", "batch", "language", "signature", "storage", "test_mode", "created_at" ] } ``` ## Response 202: Queued (`async: true`) ```json { "type": "object", "properties": { "id": { "type": "string" }, "object": { "const": "document" }, "status": { "enum": [ "queued", "rendering", "rendered", "failed", "expired" ], "type": "string" }, "template": { "type": "string" }, "version": { "anyOf": [ { "type": "number" }, { "type": "null" } ] }, "filename": { "type": "string" }, "format": { "enum": [ "pdf", "png", "xml" ], "type": "string", "description": "`xml` for XRechnung and Peppol BIS e-invoices." }, "content_type": { "type": "string", "description": "`application/pdf`, `image/png` or `application/xml`." }, "image": { "anyOf": [ { "type": "object", "properties": { "page": { "type": "number", "description": "The page that was rendered (1-based)." }, "scale": { "type": "number", "description": "Pixels per point: 2 = 144 dpi." }, "width": { "anyOf": [ { "type": "number" }, { "type": "null" } ], "description": "Pixel width, once rendered." }, "height": { "anyOf": [ { "type": "number" }, { "type": "null" } ], "description": "Pixel height, once rendered." } }, "required": [ "page", "scale", "width", "height" ] }, { "type": "null" } ], "description": "Set for `png` documents." }, "pages": { "anyOf": [ { "type": "number" }, { "type": "null" } ], "description": "Pages in the file (a PNG is one page; null for XML)." }, "size_bytes": { "anyOf": [ { "type": "number" }, { "type": "null" } ] }, "url": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "Signed download URL while the document is retained." }, "expires_at": { "anyOf": [ { "type": "string", "format": "date-time" }, { "type": "null" } ] }, "error": { "anyOf": [ { "type": "object", "properties": { "code": { "type": "string" }, "message": { "type": "string" }, "field": { "anyOf": [ { "type": "string" }, { "type": "null" } ] } }, "required": [ "code", "message", "field" ] }, { "type": "null" } ] }, "einvoice": { "anyOf": [ { "type": "object", "properties": { "format": { "enum": [ "factur-x", "xrechnung", "peppol" ], "type": "string", "description": "`factur-x`: Factur-X 1.0 / ZUGFeRD 2.x hybrid invoice, a PDF/A-3 with the CII XML embedded. `xrechnung`: XRechnung 3.0 (German CIUS) as XML. `peppol`: Peppol BIS Billing 3.0 as UBL XML." }, "syntax": { "enum": [ "cii", "ubl" ], "type": "string", "description": "XML syntax: UN/CEFACT CII (Factur-X, XRechnung on request) or OASIS UBL 2.1 (XRechnung default, Peppol)." }, "profile": { "type": "string", "description": "`EN 16931`, `XRechnung 3.0` or `Peppol BIS Billing 3.0`." }, "customization_id": { "type": "string", "description": "Specification identifier (BT-24) written into the XML." }, "attachment": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "File name of the XML embedded in the PDF; null when the document is the XML itself." } }, "required": [ "format", "syntax", "profile", "customization_id", "attachment" ] }, { "type": "null" } ], "description": "Set when the document is or carries an e-invoice (templates with e-invoicing on)." }, "batch": { "anyOf": [ { "type": "object", "properties": { "id": { "type": "string" }, "index": { "type": "number", "description": "Position of the item in the batch's `items`." } }, "required": [ "id", "index" ] }, { "type": "null" } ], "description": "Set for documents rendered as part of a batch." }, "language": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "Language the document was rendered in (one of the template's `languages`); null for documents rendered before templates had languages." }, "signature": { "anyOf": [ { "type": "object", "properties": { "certificate": { "type": "string", "description": "Id of the workspace certificate that signed the PDF." }, "certificate_name": { "type": "string" }, "subject": { "type": "string", "description": "The signer, from the certificate." }, "level": { "enum": [ "B-B", "B-T" ], "type": "string", "description": "PAdES baseline level (ETSI EN 319 142-1): `B-T` carries a trusted timestamp from a timestamp authority, `B-B` does not." }, "signed_at": { "type": "string", "format": "date-time" }, "test_certificate": { "type": "boolean", "description": "Signed with a Druckling test certificate, which proves nothing about the signer." } }, "required": [ "certificate", "certificate_name", "subject", "level", "signed_at", "test_certificate" ] }, { "type": "null" } ], "description": "Set when the PDF carries a digital signature (PAdES) applied by Druckling." }, "storage": { "anyOf": [ { "type": "object", "properties": { "bucket": { "type": "string", "description": "Id of the bucket connection (Storage page)." }, "status": { "enum": [ "pending", "delivered", "failed" ], "type": "string", "description": "`pending` until the file is uploaded (retried with backoff for about 2.5 hours), then `delivered` or `failed`." }, "key": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "Object key in your bucket, from the bucket's path template." }, "error": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "What the bucket answered on the last failed attempt, e.g. `403 AccessDenied: Access Denied`." }, "attempts": { "type": "number" }, "delivered_at": { "anyOf": [ { "type": "string", "format": "date-time" }, { "type": "null" } ] } }, "required": [ "bucket", "status", "key", "error", "attempts", "delivered_at" ] }, { "type": "null" } ], "description": "Set when the document is also copied to your own S3-compatible bucket (request `storage`, or the template's bucket rule)." }, "test_mode": { "type": "boolean" }, "created_at": { "type": "string", "format": "date-time" } }, "required": [ "id", "object", "status", "template", "version", "filename", "format", "content_type", "image", "pages", "size_bytes", "url", "expires_at", "error", "einvoice", "batch", "language", "signature", "storage", "test_mode", "created_at" ] } ``` # Retrieve a document (/docs/api-reference/documents/get) `GET https://druckling-nine.vercel.app/v1/documents/{id}` ## Parameters | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `id` | path | string | yes | | ## Response 200: OK ```json { "type": "object", "properties": { "id": { "type": "string" }, "object": { "const": "document" }, "status": { "enum": [ "queued", "rendering", "rendered", "failed", "expired" ], "type": "string" }, "template": { "type": "string" }, "version": { "anyOf": [ { "type": "number" }, { "type": "null" } ] }, "filename": { "type": "string" }, "format": { "enum": [ "pdf", "png", "xml" ], "type": "string", "description": "`xml` for XRechnung and Peppol BIS e-invoices." }, "content_type": { "type": "string", "description": "`application/pdf`, `image/png` or `application/xml`." }, "image": { "anyOf": [ { "type": "object", "properties": { "page": { "type": "number", "description": "The page that was rendered (1-based)." }, "scale": { "type": "number", "description": "Pixels per point: 2 = 144 dpi." }, "width": { "anyOf": [ { "type": "number" }, { "type": "null" } ], "description": "Pixel width, once rendered." }, "height": { "anyOf": [ { "type": "number" }, { "type": "null" } ], "description": "Pixel height, once rendered." } }, "required": [ "page", "scale", "width", "height" ] }, { "type": "null" } ], "description": "Set for `png` documents." }, "pages": { "anyOf": [ { "type": "number" }, { "type": "null" } ], "description": "Pages in the file (a PNG is one page; null for XML)." }, "size_bytes": { "anyOf": [ { "type": "number" }, { "type": "null" } ] }, "url": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "Signed download URL while the document is retained." }, "expires_at": { "anyOf": [ { "type": "string", "format": "date-time" }, { "type": "null" } ] }, "error": { "anyOf": [ { "type": "object", "properties": { "code": { "type": "string" }, "message": { "type": "string" }, "field": { "anyOf": [ { "type": "string" }, { "type": "null" } ] } }, "required": [ "code", "message", "field" ] }, { "type": "null" } ] }, "einvoice": { "anyOf": [ { "type": "object", "properties": { "format": { "enum": [ "factur-x", "xrechnung", "peppol" ], "type": "string", "description": "`factur-x`: Factur-X 1.0 / ZUGFeRD 2.x hybrid invoice, a PDF/A-3 with the CII XML embedded. `xrechnung`: XRechnung 3.0 (German CIUS) as XML. `peppol`: Peppol BIS Billing 3.0 as UBL XML." }, "syntax": { "enum": [ "cii", "ubl" ], "type": "string", "description": "XML syntax: UN/CEFACT CII (Factur-X, XRechnung on request) or OASIS UBL 2.1 (XRechnung default, Peppol)." }, "profile": { "type": "string", "description": "`EN 16931`, `XRechnung 3.0` or `Peppol BIS Billing 3.0`." }, "customization_id": { "type": "string", "description": "Specification identifier (BT-24) written into the XML." }, "attachment": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "File name of the XML embedded in the PDF; null when the document is the XML itself." } }, "required": [ "format", "syntax", "profile", "customization_id", "attachment" ] }, { "type": "null" } ], "description": "Set when the document is or carries an e-invoice (templates with e-invoicing on)." }, "batch": { "anyOf": [ { "type": "object", "properties": { "id": { "type": "string" }, "index": { "type": "number", "description": "Position of the item in the batch's `items`." } }, "required": [ "id", "index" ] }, { "type": "null" } ], "description": "Set for documents rendered as part of a batch." }, "language": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "Language the document was rendered in (one of the template's `languages`); null for documents rendered before templates had languages." }, "signature": { "anyOf": [ { "type": "object", "properties": { "certificate": { "type": "string", "description": "Id of the workspace certificate that signed the PDF." }, "certificate_name": { "type": "string" }, "subject": { "type": "string", "description": "The signer, from the certificate." }, "level": { "enum": [ "B-B", "B-T" ], "type": "string", "description": "PAdES baseline level (ETSI EN 319 142-1): `B-T` carries a trusted timestamp from a timestamp authority, `B-B` does not." }, "signed_at": { "type": "string", "format": "date-time" }, "test_certificate": { "type": "boolean", "description": "Signed with a Druckling test certificate, which proves nothing about the signer." } }, "required": [ "certificate", "certificate_name", "subject", "level", "signed_at", "test_certificate" ] }, { "type": "null" } ], "description": "Set when the PDF carries a digital signature (PAdES) applied by Druckling." }, "storage": { "anyOf": [ { "type": "object", "properties": { "bucket": { "type": "string", "description": "Id of the bucket connection (Storage page)." }, "status": { "enum": [ "pending", "delivered", "failed" ], "type": "string", "description": "`pending` until the file is uploaded (retried with backoff for about 2.5 hours), then `delivered` or `failed`." }, "key": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "Object key in your bucket, from the bucket's path template." }, "error": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "What the bucket answered on the last failed attempt, e.g. `403 AccessDenied: Access Denied`." }, "attempts": { "type": "number" }, "delivered_at": { "anyOf": [ { "type": "string", "format": "date-time" }, { "type": "null" } ] } }, "required": [ "bucket", "status", "key", "error", "attempts", "delivered_at" ] }, { "type": "null" } ], "description": "Set when the document is also copied to your own S3-compatible bucket (request `storage`, or the template's bucket rule)." }, "test_mode": { "type": "boolean" }, "created_at": { "type": "string", "format": "date-time" } }, "required": [ "id", "object", "status", "template", "version", "filename", "format", "content_type", "image", "pages", "size_bytes", "url", "expires_at", "error", "einvoice", "batch", "language", "signature", "storage", "test_mode", "created_at" ] } ``` # List a document's share links (/docs/api-reference/share-links/list) `GET https://druckling-nine.vercel.app/v1/documents/{id}/share_links` ## Parameters | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `id` | path | string | yes | | ## Response 200: OK ```json { "type": "object", "properties": { "object": { "const": "list" }, "data": { "type": "array", "items": { "type": "object", "properties": { "id": { "type": "string" }, "object": { "const": "share_link" }, "document": { "type": "string" }, "url": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "The public link. Returned only when the link is created: Druckling keeps a hash of it, not the link itself." }, "hint": { "type": "string", "description": "Last four characters of the link, to tell links apart." }, "status": { "enum": [ "active", "expired", "revoked" ], "type": "string" }, "expires_at": { "type": "string", "format": "date-time" }, "revoked_at": { "anyOf": [ { "type": "string", "format": "date-time" }, { "type": "null" } ] }, "test_mode": { "type": "boolean" }, "created_at": { "type": "string", "format": "date-time" } }, "required": [ "id", "object", "document", "url", "hint", "status", "expires_at", "revoked_at", "test_mode", "created_at" ] } } }, "required": [ "object", "data" ] } ``` # Create a share link (/docs/api-reference/share-links/create) > Creates a public, unguessable link to a rendered document that anyone can open without an API key, until it expires or is revoked. `POST https://druckling-nine.vercel.app/v1/documents/{id}/share_links` Creates a public, unguessable link to a rendered document that anyone can open without an API key, until it expires or is revoked. The link never outlives the file: `expires_at` is capped by the document's retention. The `url` is returned only here. ## Parameters | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `id` | path | string | yes | | ## Request body (JSON Schema) ```json { "type": "object", "properties": { "expires_in_days": { "type": "integer", "minimum": 1, "maximum": 30, "description": "Days until the link stops working (default 7, at most 30)." } } } ``` ## Response 201: OK ```json { "type": "object", "properties": { "id": { "type": "string" }, "object": { "const": "share_link" }, "document": { "type": "string" }, "url": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "The public link. Returned only when the link is created: Druckling keeps a hash of it, not the link itself." }, "hint": { "type": "string", "description": "Last four characters of the link, to tell links apart." }, "status": { "enum": [ "active", "expired", "revoked" ], "type": "string" }, "expires_at": { "type": "string", "format": "date-time" }, "revoked_at": { "anyOf": [ { "type": "string", "format": "date-time" }, { "type": "null" } ] }, "test_mode": { "type": "boolean" }, "created_at": { "type": "string", "format": "date-time" } }, "required": [ "id", "object", "document", "url", "hint", "status", "expires_at", "revoked_at", "test_mode", "created_at" ] } ``` # Revoke a share link (/docs/api-reference/share-links/revoke) > The link stops working immediately (410 Gone). `DELETE https://druckling-nine.vercel.app/v1/documents/{id}/share_links/{share_link_id}` The link stops working immediately (410 Gone). ## Parameters | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `id` | path | string | yes | | | `share_link_id` | path | string | yes | | ## Response 200: OK ```json { "type": "object", "properties": { "id": { "type": "string" }, "object": { "const": "share_link" }, "document": { "type": "string" }, "url": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "The public link. Returned only when the link is created: Druckling keeps a hash of it, not the link itself." }, "hint": { "type": "string", "description": "Last four characters of the link, to tell links apart." }, "status": { "enum": [ "active", "expired", "revoked" ], "type": "string" }, "expires_at": { "type": "string", "format": "date-time" }, "revoked_at": { "anyOf": [ { "type": "string", "format": "date-time" }, { "type": "null" } ] }, "test_mode": { "type": "boolean" }, "created_at": { "type": "string", "format": "date-time" } }, "required": [ "id", "object", "document", "url", "hint", "status", "expires_at", "revoked_at", "test_mode", "created_at" ] } ``` # List batches (/docs/api-reference/batches/list) `GET https://druckling-nine.vercel.app/v1/batches` ## Parameters | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `limit` | query | integer | no | | | `cursor` | query | string | no | | | `status` | query | string | no | | ## Response 200: OK ```json { "type": "object", "properties": { "object": { "const": "list" }, "data": { "type": "array", "items": { "type": "object", "properties": { "id": { "type": "string" }, "object": { "const": "batch" }, "status": { "enum": [ "queued", "running", "completed", "failed", "canceled" ], "type": "string", "description": "`queued` → `running` → `completed` (ZIP ready), `failed` (nothing rendered, or the ZIP couldn't be built) or `canceled`." }, "template": { "type": "string" }, "version": { "type": "number" }, "filename_pattern": { "anyOf": [ { "type": "string" }, { "type": "null" } ] }, "counts": { "type": "object", "properties": { "total": { "type": "number" }, "pending": { "type": "number" }, "rendered": { "type": "number" }, "failed": { "type": "number" }, "canceled": { "type": "number" } }, "required": [ "total", "pending", "rendered", "failed", "canceled" ], "description": "Items by outcome; `pending` is queued or rendering." }, "zip_url": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "Signed download URL of the ZIP with every rendered file (PDFs, or XML e-invoices), once the batch completed and while the ZIP is retained." }, "zip_size_bytes": { "anyOf": [ { "type": "number" }, { "type": "null" } ] }, "zip_expires_at": { "anyOf": [ { "type": "string", "format": "date-time" }, { "type": "null" } ], "description": "When the ZIP is deleted (the file retention period)." }, "error": { "anyOf": [ { "type": "object", "properties": { "code": { "type": "string" }, "message": { "type": "string" } }, "required": [ "code", "message" ] }, { "type": "null" } ] }, "test_mode": { "type": "boolean" }, "created_at": { "type": "string", "format": "date-time" }, "finished_at": { "anyOf": [ { "type": "string", "format": "date-time" }, { "type": "null" } ] } }, "required": [ "id", "object", "status", "template", "version", "filename_pattern", "counts", "zip_url", "zip_size_bytes", "zip_expires_at", "error", "test_mode", "created_at", "finished_at" ] } }, "next_cursor": { "anyOf": [ { "type": "string" }, { "type": "null" } ] } }, "required": [ "object", "data", "next_cursor" ] } ``` # Start a batch (/docs/api-reference/batches/create) > Renders one template for many payloads. `POST https://druckling-nine.vercel.app/v1/batches` Renders one template for many payloads. Every item's `data` is validated first: if any item is invalid nothing is rendered and the answer is 422 with `data.errors` listing the first invalid items' `index`, `field` and `message` (`data.invalidItems` counts them all). Otherwise each item becomes an asynchronous document (its `batch` set) and the answer is 202. Poll `GET /batches/{id}` or subscribe to `batch.completed`; a completed batch has a `zip_url` with every rendered PDF. Up to 1,000 items and 4 MB per request. Live batches must fit in the plan's documents left today and this month (429 `quota_exceeded`). ## Request body (JSON Schema) ```json { "type": "object", "properties": { "template": { "type": "string", "description": "Template slug, e.g. invoice-standard" }, "version": { "anyOf": [ { "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991, "exclusiveMinimum": 0 }, { "const": "latest" } ], "description": "Pinned version or `latest` (default)." }, "items": { "type": "array", "minItems": 1, "maxItems": 1000, "items": { "type": "object", "properties": { "data": { "type": "object", "propertyNames": { "type": "string" }, "additionalProperties": {}, "description": "Payload matching the template schema." }, "filename": { "type": "string", "maxLength": 200, "description": "File name of this item's PDF; overrides `filename_pattern`." }, "language": { "type": "string", "maxLength": 35, "description": "This item's language; overrides the batch's `language`." } }, "required": [ "data" ] } }, "language": { "type": "string", "maxLength": 35, "description": "Language of every item without its own `language`: one of the template's `languages` (default: its default language). Unknown languages are rejected with 422 on `language` or `items.{n}.language`." }, "filename_pattern": { "type": "string", "maxLength": 200, "description": "File names from each item's data, e.g. `invoice-{{invoice.number}}.pdf`. Names are made unique within the batch; default `{template}-{n}.pdf`. XRechnung and Peppol templates produce XML e-invoices, named `.xml`." }, "storage": { "anyOf": [ { "type": "object", "properties": { "bucket": { "type": "string", "minLength": 1, "maxLength": 64, "description": "A bucket id from the Storage page, or `default` for the workspace's default bucket." } }, "required": [ "bucket" ] }, { "const": false } ], "description": "Copy every item's file to one of your own buckets, as for a single render." } }, "required": [ "template", "items" ] } ``` ## Response 202: OK ```json { "type": "object", "properties": { "id": { "type": "string" }, "object": { "const": "batch" }, "status": { "enum": [ "queued", "running", "completed", "failed", "canceled" ], "type": "string", "description": "`queued` → `running` → `completed` (ZIP ready), `failed` (nothing rendered, or the ZIP couldn't be built) or `canceled`." }, "template": { "type": "string" }, "version": { "type": "number" }, "filename_pattern": { "anyOf": [ { "type": "string" }, { "type": "null" } ] }, "counts": { "type": "object", "properties": { "total": { "type": "number" }, "pending": { "type": "number" }, "rendered": { "type": "number" }, "failed": { "type": "number" }, "canceled": { "type": "number" } }, "required": [ "total", "pending", "rendered", "failed", "canceled" ], "description": "Items by outcome; `pending` is queued or rendering." }, "zip_url": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "Signed download URL of the ZIP with every rendered file (PDFs, or XML e-invoices), once the batch completed and while the ZIP is retained." }, "zip_size_bytes": { "anyOf": [ { "type": "number" }, { "type": "null" } ] }, "zip_expires_at": { "anyOf": [ { "type": "string", "format": "date-time" }, { "type": "null" } ], "description": "When the ZIP is deleted (the file retention period)." }, "error": { "anyOf": [ { "type": "object", "properties": { "code": { "type": "string" }, "message": { "type": "string" } }, "required": [ "code", "message" ] }, { "type": "null" } ] }, "test_mode": { "type": "boolean" }, "created_at": { "type": "string", "format": "date-time" }, "finished_at": { "anyOf": [ { "type": "string", "format": "date-time" }, { "type": "null" } ] } }, "required": [ "id", "object", "status", "template", "version", "filename_pattern", "counts", "zip_url", "zip_size_bytes", "zip_expires_at", "error", "test_mode", "created_at", "finished_at" ] } ``` # Retrieve a batch (/docs/api-reference/batches/get) `GET https://druckling-nine.vercel.app/v1/batches/{id}` ## Parameters | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `id` | path | string | yes | | ## Response 200: OK ```json { "type": "object", "properties": { "id": { "type": "string" }, "object": { "const": "batch" }, "status": { "enum": [ "queued", "running", "completed", "failed", "canceled" ], "type": "string", "description": "`queued` → `running` → `completed` (ZIP ready), `failed` (nothing rendered, or the ZIP couldn't be built) or `canceled`." }, "template": { "type": "string" }, "version": { "type": "number" }, "filename_pattern": { "anyOf": [ { "type": "string" }, { "type": "null" } ] }, "counts": { "type": "object", "properties": { "total": { "type": "number" }, "pending": { "type": "number" }, "rendered": { "type": "number" }, "failed": { "type": "number" }, "canceled": { "type": "number" } }, "required": [ "total", "pending", "rendered", "failed", "canceled" ], "description": "Items by outcome; `pending` is queued or rendering." }, "zip_url": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "Signed download URL of the ZIP with every rendered file (PDFs, or XML e-invoices), once the batch completed and while the ZIP is retained." }, "zip_size_bytes": { "anyOf": [ { "type": "number" }, { "type": "null" } ] }, "zip_expires_at": { "anyOf": [ { "type": "string", "format": "date-time" }, { "type": "null" } ], "description": "When the ZIP is deleted (the file retention period)." }, "error": { "anyOf": [ { "type": "object", "properties": { "code": { "type": "string" }, "message": { "type": "string" } }, "required": [ "code", "message" ] }, { "type": "null" } ] }, "test_mode": { "type": "boolean" }, "created_at": { "type": "string", "format": "date-time" }, "finished_at": { "anyOf": [ { "type": "string", "format": "date-time" }, { "type": "null" } ] } }, "required": [ "id", "object", "status", "template", "version", "filename_pattern", "counts", "zip_url", "zip_size_bytes", "zip_expires_at", "error", "test_mode", "created_at", "finished_at" ] } ``` # List a batch's documents (/docs/api-reference/batches/documents) > The batch's documents in item order. `GET https://druckling-nine.vercel.app/v1/batches/{id}/documents` The batch's documents in item order. Filter by `outcome` (the keys of `counts`), e.g. `failed` for the items that need attention. ## Parameters | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `id` | path | string | yes | | | `outcome` | query | string | no | | | `limit` | query | integer | no | | | `cursor` | query | string | no | | ## Response 200: OK ```json { "type": "object", "properties": { "object": { "const": "list" }, "data": { "type": "array", "items": { "type": "object", "properties": { "id": { "type": "string" }, "object": { "const": "document" }, "status": { "enum": [ "queued", "rendering", "rendered", "failed", "expired" ], "type": "string" }, "template": { "type": "string" }, "version": { "anyOf": [ { "type": "number" }, { "type": "null" } ] }, "filename": { "type": "string" }, "format": { "enum": [ "pdf", "png", "xml" ], "type": "string", "description": "`xml` for XRechnung and Peppol BIS e-invoices." }, "content_type": { "type": "string", "description": "`application/pdf`, `image/png` or `application/xml`." }, "image": { "anyOf": [ { "type": "object", "properties": { "page": { "type": "number", "description": "The page that was rendered (1-based)." }, "scale": { "type": "number", "description": "Pixels per point: 2 = 144 dpi." }, "width": { "anyOf": [ { "type": "number" }, { "type": "null" } ], "description": "Pixel width, once rendered." }, "height": { "anyOf": [ { "type": "number" }, { "type": "null" } ], "description": "Pixel height, once rendered." } }, "required": [ "page", "scale", "width", "height" ] }, { "type": "null" } ], "description": "Set for `png` documents." }, "pages": { "anyOf": [ { "type": "number" }, { "type": "null" } ], "description": "Pages in the file (a PNG is one page; null for XML)." }, "size_bytes": { "anyOf": [ { "type": "number" }, { "type": "null" } ] }, "url": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "Signed download URL while the document is retained." }, "expires_at": { "anyOf": [ { "type": "string", "format": "date-time" }, { "type": "null" } ] }, "error": { "anyOf": [ { "type": "object", "properties": { "code": { "type": "string" }, "message": { "type": "string" }, "field": { "anyOf": [ { "type": "string" }, { "type": "null" } ] } }, "required": [ "code", "message", "field" ] }, { "type": "null" } ] }, "einvoice": { "anyOf": [ { "type": "object", "properties": { "format": { "enum": [ "factur-x", "xrechnung", "peppol" ], "type": "string", "description": "`factur-x`: Factur-X 1.0 / ZUGFeRD 2.x hybrid invoice, a PDF/A-3 with the CII XML embedded. `xrechnung`: XRechnung 3.0 (German CIUS) as XML. `peppol`: Peppol BIS Billing 3.0 as UBL XML." }, "syntax": { "enum": [ "cii", "ubl" ], "type": "string", "description": "XML syntax: UN/CEFACT CII (Factur-X, XRechnung on request) or OASIS UBL 2.1 (XRechnung default, Peppol)." }, "profile": { "type": "string", "description": "`EN 16931`, `XRechnung 3.0` or `Peppol BIS Billing 3.0`." }, "customization_id": { "type": "string", "description": "Specification identifier (BT-24) written into the XML." }, "attachment": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "File name of the XML embedded in the PDF; null when the document is the XML itself." } }, "required": [ "format", "syntax", "profile", "customization_id", "attachment" ] }, { "type": "null" } ], "description": "Set when the document is or carries an e-invoice (templates with e-invoicing on)." }, "batch": { "anyOf": [ { "type": "object", "properties": { "id": { "type": "string" }, "index": { "type": "number", "description": "Position of the item in the batch's `items`." } }, "required": [ "id", "index" ] }, { "type": "null" } ], "description": "Set for documents rendered as part of a batch." }, "language": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "Language the document was rendered in (one of the template's `languages`); null for documents rendered before templates had languages." }, "signature": { "anyOf": [ { "type": "object", "properties": { "certificate": { "type": "string", "description": "Id of the workspace certificate that signed the PDF." }, "certificate_name": { "type": "string" }, "subject": { "type": "string", "description": "The signer, from the certificate." }, "level": { "enum": [ "B-B", "B-T" ], "type": "string", "description": "PAdES baseline level (ETSI EN 319 142-1): `B-T` carries a trusted timestamp from a timestamp authority, `B-B` does not." }, "signed_at": { "type": "string", "format": "date-time" }, "test_certificate": { "type": "boolean", "description": "Signed with a Druckling test certificate, which proves nothing about the signer." } }, "required": [ "certificate", "certificate_name", "subject", "level", "signed_at", "test_certificate" ] }, { "type": "null" } ], "description": "Set when the PDF carries a digital signature (PAdES) applied by Druckling." }, "storage": { "anyOf": [ { "type": "object", "properties": { "bucket": { "type": "string", "description": "Id of the bucket connection (Storage page)." }, "status": { "enum": [ "pending", "delivered", "failed" ], "type": "string", "description": "`pending` until the file is uploaded (retried with backoff for about 2.5 hours), then `delivered` or `failed`." }, "key": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "Object key in your bucket, from the bucket's path template." }, "error": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "What the bucket answered on the last failed attempt, e.g. `403 AccessDenied: Access Denied`." }, "attempts": { "type": "number" }, "delivered_at": { "anyOf": [ { "type": "string", "format": "date-time" }, { "type": "null" } ] } }, "required": [ "bucket", "status", "key", "error", "attempts", "delivered_at" ] }, { "type": "null" } ], "description": "Set when the document is also copied to your own S3-compatible bucket (request `storage`, or the template's bucket rule)." }, "test_mode": { "type": "boolean" }, "created_at": { "type": "string", "format": "date-time" } }, "required": [ "id", "object", "status", "template", "version", "filename", "format", "content_type", "image", "pages", "size_bytes", "url", "expires_at", "error", "einvoice", "batch", "language", "signature", "storage", "test_mode", "created_at" ] } }, "next_cursor": { "anyOf": [ { "type": "string" }, { "type": "null" } ] } }, "required": [ "object", "data", "next_cursor" ] } ``` # Cancel a batch (/docs/api-reference/batches/cancel) > Items that haven't started rendering are canceled (failed documents with error code canceled); renders already running finish. `POST https://druckling-nine.vercel.app/v1/batches/{id}/cancel` Items that haven't started rendering are canceled (`failed` documents with error code `canceled`); renders already running finish. A canceled batch has no ZIP. 409 once the batch has finished. ## Parameters | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `id` | path | string | yes | | ## Response 200: OK ```json { "type": "object", "properties": { "id": { "type": "string" }, "object": { "const": "batch" }, "status": { "enum": [ "queued", "running", "completed", "failed", "canceled" ], "type": "string", "description": "`queued` → `running` → `completed` (ZIP ready), `failed` (nothing rendered, or the ZIP couldn't be built) or `canceled`." }, "template": { "type": "string" }, "version": { "type": "number" }, "filename_pattern": { "anyOf": [ { "type": "string" }, { "type": "null" } ] }, "counts": { "type": "object", "properties": { "total": { "type": "number" }, "pending": { "type": "number" }, "rendered": { "type": "number" }, "failed": { "type": "number" }, "canceled": { "type": "number" } }, "required": [ "total", "pending", "rendered", "failed", "canceled" ], "description": "Items by outcome; `pending` is queued or rendering." }, "zip_url": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "description": "Signed download URL of the ZIP with every rendered file (PDFs, or XML e-invoices), once the batch completed and while the ZIP is retained." }, "zip_size_bytes": { "anyOf": [ { "type": "number" }, { "type": "null" } ] }, "zip_expires_at": { "anyOf": [ { "type": "string", "format": "date-time" }, { "type": "null" } ], "description": "When the ZIP is deleted (the file retention period)." }, "error": { "anyOf": [ { "type": "object", "properties": { "code": { "type": "string" }, "message": { "type": "string" } }, "required": [ "code", "message" ] }, { "type": "null" } ] }, "test_mode": { "type": "boolean" }, "created_at": { "type": "string", "format": "date-time" }, "finished_at": { "anyOf": [ { "type": "string", "format": "date-time" }, { "type": "null" } ] } }, "required": [ "id", "object", "status", "template", "version", "filename_pattern", "counts", "zip_url", "zip_size_bytes", "zip_expires_at", "error", "test_mode", "created_at", "finished_at" ] } ``` # List templates (/docs/api-reference/templates/list) `GET https://druckling-nine.vercel.app/v1/templates` ## Response 200: OK ```json { "type": "object", "properties": { "object": { "const": "list" }, "data": { "type": "array", "items": { "type": "object", "properties": { "id": { "type": "string" }, "object": { "const": "template" }, "slug": { "type": "string" }, "name": { "type": "string" }, "status": { "enum": [ "draft", "published" ], "type": "string" }, "latest_version": { "anyOf": [ { "type": "number" }, { "type": "null" } ] }, "required_fields": { "type": "array", "items": { "type": "string" } }, "language": { "type": "string", "description": "Default language, used when a render names none." }, "languages": { "type": "array", "items": { "type": "string" }, "description": "Every language the template renders in (pass one as `language`), default first. From the latest published version, or the draft if never published." }, "updated_at": { "type": "string", "format": "date-time" } }, "required": [ "id", "object", "slug", "name", "status", "latest_version", "required_fields", "language", "languages", "updated_at" ] } } }, "required": [ "object", "data" ] } ``` # Retrieve a template and its JSON Schema (/docs/api-reference/templates/get) `GET https://druckling-nine.vercel.app/v1/templates/{slug}` ## Parameters | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `slug` | path | string | yes | | ## Response 200: OK ```json { "type": "object", "properties": { "id": { "type": "string" }, "object": { "const": "template" }, "slug": { "type": "string" }, "name": { "type": "string" }, "status": { "enum": [ "draft", "published" ], "type": "string" }, "latest_version": { "anyOf": [ { "type": "number" }, { "type": "null" } ] }, "required_fields": { "type": "array", "items": { "type": "string" } }, "language": { "type": "string", "description": "Default language, used when a render names none." }, "languages": { "type": "array", "items": { "type": "string" }, "description": "Every language the template renders in (pass one as `language`), default first. From the latest published version, or the draft if never published." }, "updated_at": { "type": "string", "format": "date-time" }, "json_schema": { "type": "object", "propertyNames": { "type": "string" }, "additionalProperties": {} }, "sample_data": { "type": "object", "propertyNames": { "type": "string" }, "additionalProperties": {} } }, "required": [ "id", "object", "slug", "name", "status", "latest_version", "required_fields", "language", "languages", "updated_at", "json_schema", "sample_data" ] } ```