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

<Callout type="info" title="E-invoice templates">

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

</Callout>

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

<Callout type="warn" title="Keep personal data out of sample data">

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.

</Callout>

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

<Cards>
  <Card title="Template strings" href="/docs/concepts/template-strings">
    Bind and format the values you declared.
  </Card>
  <Card title="Errors" href="/docs/concepts/errors">
    Every error code and how to handle it.
  </Card>
</Cards>
