# Render a batch

> One template, up to 100 sets of values, each its own render, in the background.

<Endpoint method="POST" path="/v1/renders/batch" />

<CodeTabs>

```bash tab="cURL"
curl -X POST https://api.muzekit.com/v1/renders/batch \
  -H "Authorization: Bearer $MUZEKIT_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "template": "product-card", "format": "png", "items": [
        { "modifications": { "title": "Blue mug" } },
        { "modifications": { "title": "Red mug" }, "size": "1080x1920" }
      ] }'
```

```javascript tab="Node"
const res = await fetch("https://api.muzekit.com/v1/renders/batch", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.MUZEKIT_SECRET_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    template: "product-card",
    format: "png",
    items: [
      { modifications: { title: "Blue mug" } },
      { modifications: { title: "Red mug" }, size: "1080x1920" },
    ],
  }),
});
const batch = await res.json();
```

```python tab="Python"
import os
import requests

# json= sends the body with Content-Type: application/json
batch = requests.post(
    "https://api.muzekit.com/v1/renders/batch",
    headers={"Authorization": f"Bearer {os.environ['MUZEKIT_SECRET_KEY']}"},
    json={
        "template": "product-card",
        "format": "png",
        "items": [
            {"modifications": {"title": "Blue mug"}},
            {"modifications": {"title": "Red mug"}, "size": "1080x1920"},
        ],
    },
).json()
```

</CodeTabs>

## Body

Everything [Create a render](/docs/api-reference/renders-create) takes, except `modifications`, which each item carries instead:

| Field | |
|---|---|
| `items` | 1 to 100 of `{ "modifications": {…}, "pages": […], "size": … }`; `pages` and `size` override the batch's for that item |

Every item is a render of its own, queued at once and rendered in the background, up to four at a time (videos two). The answer is `202` straight away; follow the renders with [List renders](/docs/api-reference/renders-list) and `?batch=bat_…`, or the `render.succeeded` and `render.failed` webhooks.

Credits are checked for the whole batch as it's queued: when they run out, that item and the rest come back `failed` with `api_credits_exhausted`, and the items before them still render. A Test environment's daily cap (`429 test_renders_exhausted`) stops the rest the same way. An item that is wrong by itself, such as a bad `size`, fails alone.

`renders` lists one entry per item, in the order of `items`. An item that couldn't start has `id: null` and its `item` index.

## Examples

### Render a batch from rows of data

Turn each row of a spreadsheet or a database query into one item. Up to 100 items a request; split longer lists into several batches.

<CodeTabs>

```bash tab="cURL"
# rows.json: [{ "name": "Blue mug", "image": "https://…" }, …]
jq '{ template: "product-card", format: "png",
      items: map({ modifications: { headline: .name, photo: .image } }) }' \
  rows.json \
  | curl https://api.muzekit.com/v1/renders/batch \
      -H "Authorization: Bearer $MUZEKIT_SECRET_KEY" \
      -H "Content-Type: application/json" \
      -d @-
```

```javascript tab="Node"
const rows = [
  { name: "Blue mug", image: "https://example.com/blue-mug.jpg" },
  { name: "Red mug", image: "https://example.com/red-mug.jpg" },
];

const res = await fetch("https://api.muzekit.com/v1/renders/batch", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.MUZEKIT_SECRET_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    template: "product-card",
    format: "png",
    items: rows.map((row) => ({
      modifications: { headline: row.name, photo: row.image },
    })),
  }),
});
const batch = await res.json(); // keep batch.id to follow it
```

```python tab="Python"
import csv
import os
import requests

# products.csv has the columns name and image
with open("products.csv") as f:
    rows = list(csv.DictReader(f))

batch = requests.post(
    "https://api.muzekit.com/v1/renders/batch",
    headers={"Authorization": f"Bearer {os.environ['MUZEKIT_SECRET_KEY']}"},
    json={
        "template": "product-card",
        "format": "png",
        "items": [
            {"modifications": {"headline": r["name"], "photo": r["image"]}}
            for r in rows
        ],
    },
).json()
```

</CodeTabs>

### Follow a batch until it's done

List the batch's renders until none is `queued` or `processing`. A batch has at most 100 renders, so `limit=100` gets them in one page.

<CodeTabs>

```bash tab="cURL"
curl "https://api.muzekit.com/v1/renders?batch=bat_Zb3x0k1PqLm2&limit=100" \
  -H "Authorization: Bearer $MUZEKIT_SECRET_KEY" \
  | jq -r '.data[] | "\(.id)\t\(.status)"'
```

```javascript tab="Node"
const url = `https://api.muzekit.com/v1/renders?batch=${batch.id}&limit=100`;
const auth = { Authorization: `Bearer ${process.env.MUZEKIT_SECRET_KEY}` };
const pending = (r) => r.status === "queued" || r.status === "processing";

let renders;
do {
  await new Promise((resolve) => setTimeout(resolve, 3000));
  renders = (await (await fetch(url, { headers: auth })).json()).data;
} while (renders.some(pending));

const files = renders.filter((r) => r.status === "succeeded");
```

```python tab="Python"
import os
import time
import requests

auth = {"Authorization": f"Bearer {os.environ['MUZEKIT_SECRET_KEY']}"}
params = {"batch": batch["id"], "limit": 100}

while True:
    time.sleep(3)
    renders = requests.get(
        "https://api.muzekit.com/v1/renders", params=params, headers=auth
    ).json()["data"]
    if not any(r["status"] in ("queued", "processing") for r in renders):
        break

files = [r for r in renders if r["status"] == "succeeded"]
```

</CodeTabs>

The list is newest first, not in item order. Items that couldn't start aren't in it: they have no render.

### Match each render to its row

Keep the render ids from the answer, in item order, next to your rows. Then each `render.succeeded` webhook (its `data.render`) or listed render finds its row.

<CodeTabs>

```bash tab="cURL"
# Item index, render id (null if it couldn't start), status
jq -r '.renders | to_entries[]
  | "\(.key)\t\(.value.id)\t\(.value.status)"' batch.json
```

```javascript tab="Node"
// batch is the answer to POST /v1/renders/batch, rows what you sent
const rowByRender = new Map();
batch.renders.forEach((render, i) => {
  if (render.id) rowByRender.set(render.id, rows[i]);
  else console.warn(`Row ${i} didn't start: ${render.error.message}`);
});

// In your webhook handler
function onRenderSucceeded(event) {
  const row = rowByRender.get(event.data.render);
  // Save event.data.outputs[0] with row
}
```

```python tab="Python"
# batch is the answer to POST /v1/renders/batch, rows what you sent
row_by_render = {}
for i, render in enumerate(batch["renders"]):
    if render["id"]:
        row_by_render[render["id"]] = rows[i]
    else:
        print(f"Row {i} didn't start: {render['error']['message']}")

# In your webhook handler
def on_render_succeeded(event):
    row = row_by_render.get(event["data"]["render"])
    # Save event["data"]["outputs"][0] with row
```

</CodeTabs>

In production, store the pairs in your database rather than in memory: renders finish after your request ends.

## Response

```json
{
  "object": "batch",
  "id": "bat_Zb3x0k1PqLm2",
  "template": "tpl_Vk1t4l9xvQv",
  "renders": [
    {
      "object": "render",
      "id": "rnd_…",
      "status": "queued",
      "outputs": [],
      "…": "…"
    },
    {
      "object": "render",
      "id": null,
      "status": "failed",
      "item": 1,
      "error": { "code": "invalid_size", "message": "…" }
    }
  ]
}
```
