# 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 }
      }
    }
  ]
}
```

<Callout type="info" title="No SDK methods yet">

The [TypeScript, Python and PHP SDKs](/docs/sdks) don't wrap the batch endpoints yet. Call them over plain HTTP, as below.

</Callout>

```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"
<?php
$ch = curl_init('https://druckling-nine.vercel.app/v1/batches');
curl_setopt_array($ch, [
    CURLOPT_POST => 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.

<Steps>
<Step>

### 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.

</Step>
<Step>

### 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`.

</Step>
<Step>

### 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.

</Step>
<Step>

### 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.

</Step>
</Steps>

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).
