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

<TypeTable
  type={{
    "data.code": {
      type: "string",
      description: "Druckling's error code, such as `schema_validation_failed`. Branch on this one. See the table below.",
    },
    "data.field": {
      type: "string | null",
      description: "Dotted path of the field the error is about, such as `customer.address` or `line_items.2.qty`. `null` when the error isn't about one field.",
    },
    code: {
      type: "string",
      description: "The general class of error that goes with the HTTP status, such as `NOT_FOUND` or `UNPROCESSABLE_CONTENT`. Several error codes share one class.",
    },
    status: {
      type: "number",
      description: "The HTTP status code, repeated in the body.",
    },
    message: {
      type: "string",
      description: "A human-readable explanation. Show it or log it, but don't parse it: the wording can change.",
    },
    defined: {
      type: "boolean",
      description: "Always `false`. You can ignore it.",
    },
  }}
/>

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<string, unknown>) {
  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.
