# Update a document

> Replace a template’s content, guarded by the revision you read.

<Endpoint method="PUT" path="/v1/templates/{id}/document" />

<CodeTabs>

```bash tab="cURL"
curl -X PUT https://api.muzekit.com/v1/templates/tpl_Vk1t4l9xvQv/document \
  -H "Authorization: Bearer $MUZEKIT_SECRET_KEY" \
  -H 'If-Match: "3"' \
  -H "Content-Type: application/json" \
  -d @document.json
```

```javascript tab="Node"
const res = await fetch(
  "https://api.muzekit.com/v1/templates/tpl_Vk1t4l9xvQv/document",
  {
    method: "PUT",
    headers: {
      Authorization: `Bearer ${process.env.MUZEKIT_SECRET_KEY}`,
      "If-Match": `"${revision}"`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ document }),
  },
);
const saved = await res.json(); // saved.revision is the new revision
```

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

saved = requests.put(
    "https://api.muzekit.com/v1/templates/tpl_Vk1t4l9xvQv/document",
    headers={
        "Authorization": f"Bearer {os.environ['MUZEKIT_SECRET_KEY']}",
        "If-Match": f'"{revision}"',
    },
    json={"document": document},
).json()
```

</CodeTabs>

`{id}` is the template's `tpl_…` id or its key. In the cURL example, `document.json` holds `{ "document": { … } }`.

## Headers

<ParamTable params={[
  { name: "If-Match", type: "string", description: "The revision you edited, e.g. \"3\". Required unless the body has revision." }
]} />

## Body

<ParamTable params={[
  { name: "document", type: "object", required: true, description: "The full document: pages, and optional meta and ext." },
  { name: "revision", type: "number", description: "The revision you edited, for clients that can't set If-Match. If-Match wins when both are sent." }
]} />

Send the revision once: in `If-Match`, or as `revision` in the body (`3`, or the string `"3"`). With neither the save answers `428 if_match_required`; a `revision` that isn't a whole number answers `400`.

A save replaces the current version in place: it doesn't add a version, and the old content is gone. [Duplicate the template](/docs/api-reference/templates-duplicate#keep-a-copy-before-you-change-a-document) first if you want to keep it. Every save sends a `template.updated` webhook, and renders the template when [render on save](/docs/webhooks#render-on-save) is on.

## Examples

### Change a text layer's words

Read the document, change the layer's `content`, and save with the revision you read. Here the layer is the one whose field key is `headline`.

<CodeTabs>

```bash tab="cURL"
URL=https://api.muzekit.com/v1/templates/product-card/document
AUTH="Authorization: Bearer $MUZEKIT_SECRET_KEY"

curl -s "$URL" -H "$AUTH" > current.json
REV=$(jq '.revision' current.json)

jq '{ document: .document }
  | (.document.pages[].elements[] | select(.parameterId == "headline")
    | .content) = "Winter sale"' current.json \
  | curl -X PUT "$URL" -H "$AUTH" -H "If-Match: \"$REV\"" \
      -H "Content-Type: application/json" -d @-
```

```javascript tab="Node"
const url = "https://api.muzekit.com/v1/templates/product-card/document";
const auth = { Authorization: `Bearer ${process.env.MUZEKIT_SECRET_KEY}` };

const { document, revision } = await (await fetch(url, { headers: auth })).json();
for (const page of document.pages) {
  for (const el of page.elements ?? []) {
    if (el.parameterId === "headline") el.content = "Winter sale";
  }
}

const res = await fetch(url, {
  method: "PUT",
  headers: {
    ...auth,
    "If-Match": `"${revision}"`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ document }),
});
```

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

url = "https://api.muzekit.com/v1/templates/product-card/document"
auth = {"Authorization": f"Bearer {os.environ['MUZEKIT_SECRET_KEY']}"}

current = requests.get(url, headers=auth).json()
document = current["document"]
for page in document["pages"]:
    for el in page.get("elements", []):
        if el.get("parameterId") == "headline":
            el["content"] = "Winter sale"

res = requests.put(
    url,
    headers={**auth, "If-Match": f'"{current["revision"]}"'},
    json={"document": document},
)
```

</CodeTabs>

To change a value for one render only, send it in `modifications` when you [render](/docs/api-reference/renders-create); the template stays as it is.

### Send the revision in the body

Some clients, such as an AI agent's HTTP tool, can't set headers. Put the revision you read next to the document instead.

<CodeTabs>

```bash tab="cURL"
curl -X PUT https://api.muzekit.com/v1/templates/product-card/document \
  -H "Authorization: Bearer $MUZEKIT_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "revision": 3, "document": { "pages": [ … ] } }'
```

```javascript tab="Node"
const res = await fetch(
  "https://api.muzekit.com/v1/templates/product-card/document",
  {
    method: "PUT",
    headers: {
      Authorization: `Bearer ${process.env.MUZEKIT_SECRET_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ revision, document }),
  },
);
```

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

res = requests.put(
    "https://api.muzekit.com/v1/templates/product-card/document",
    headers={"Authorization": f"Bearer {os.environ['MUZEKIT_SECRET_KEY']}"},
    json={"revision": revision, "document": document},
)
```

</CodeTabs>

### Retry when someone saved first

A user may save in the editor between your read and your write. Then the save answers `409 revision_conflict`: read again, apply your change to the new document, and save again.

<CodeTabs>

```bash tab="cURL"
# A 409 means: run the read and the change again
curl -s -o /dev/null -w "%{http_code}\n" -X PUT \
  https://api.muzekit.com/v1/templates/product-card/document \
  -H "Authorization: Bearer $MUZEKIT_SECRET_KEY" \
  -H 'If-Match: "3"' \
  -H "Content-Type: application/json" \
  -d @document.json
```

```javascript tab="Node"
const url = "https://api.muzekit.com/v1/templates/product-card/document";
const auth = { Authorization: `Bearer ${process.env.MUZEKIT_SECRET_KEY}` };

// change(document) edits the document you read
async function save(change, tries = 3) {
  for (let i = 0; i < tries; i++) {
    const { document, revision } = await (await fetch(url, { headers: auth })).json();
    change(document);
    const res = await fetch(url, {
      method: "PUT",
      headers: {
        ...auth,
        "If-Match": `"${revision}"`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ document }),
    });
    if (res.status !== 409) return res.json();
  }
  throw new Error("The template kept changing; try again later");
}
```

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

url = "https://api.muzekit.com/v1/templates/product-card/document"
auth = {"Authorization": f"Bearer {os.environ['MUZEKIT_SECRET_KEY']}"}

# change(document) edits the document you read
def save(change, tries=3):
    for _ in range(tries):
        current = requests.get(url, headers=auth).json()
        change(current["document"])
        res = requests.put(
            url,
            headers={**auth, "If-Match": f'"{current["revision"]}"'},
            json={"document": current["document"]},
        )
        if res.status_code != 409:
            return res.json()
    raise RuntimeError("The template kept changing; try again later")
```

</CodeTabs>

### Copy one template's design into another

Read the source's document, read the target's revision, and save the source's document over the target. The target keeps its id, key and name, so renders and sessions that name it now get the new design.

<CodeTabs>

```bash tab="cURL"
API=https://api.muzekit.com/v1
AUTH="Authorization: Bearer $MUZEKIT_SECRET_KEY"

REV=$(curl -s "$API/templates/product-card/document" -H "$AUTH" | jq '.revision')

curl -s "$API/templates/product-card-draft/document" -H "$AUTH" \
  | jq '{ document }' \
  | curl -X PUT "$API/templates/product-card/document" -H "$AUTH" \
      -H "If-Match: \"$REV\"" -H "Content-Type: application/json" -d @-
```

```javascript tab="Node"
const API = "https://api.muzekit.com/v1";
const auth = { Authorization: `Bearer ${process.env.MUZEKIT_SECRET_KEY}` };
const read = async (id) =>
  (await fetch(`${API}/templates/${id}/document`, { headers: auth })).json();

const source = await read("product-card-draft");
const target = await read("product-card");

await fetch(`${API}/templates/product-card/document`, {
  method: "PUT",
  headers: {
    ...auth,
    "If-Match": `"${target.revision}"`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ document: source.document }),
});
```

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

API = "https://api.muzekit.com/v1"
auth = {"Authorization": f"Bearer {os.environ['MUZEKIT_SECRET_KEY']}"}

def read(template):
    return requests.get(f"{API}/templates/{template}/document", headers=auth).json()

source = read("product-card-draft")
target = read("product-card")

requests.put(
    f"{API}/templates/product-card/document",
    headers={**auth, "If-Match": f'"{target["revision"]}"'},
    json={"document": source["document"]},
)
```

</CodeTabs>

The source can be in another environment: read it with that environment's key. To make a new template from a document instead, see [Get a document](/docs/api-reference/templates-document-get#copy-a-template-into-another-environment).

## Response

```json
{
  "object": "document",
  "template": "tpl_Vk1t4l9xvQv",
  "version": "ver_Lp0sQ7dXk2m",
  "revision": 4
}
```

The `ETag` header carries the new revision. Send it as `If-Match` on your next save.

| Error | When |
|---|---|
| `409 revision_conflict` | Someone saved since you read it: fetch the document again and reapply your change |
| `428 if_match_required` | The request has no `If-Match` |
| `400 invalid_document` | The document breaks a rule; `problems` lists every one |
| `404 template_not_found` | No template with this id or key in this environment |
