
# ETags and If-Match

Several people, scripts and assistants can edit the same page. To make sure you change the version you read, send its `ETag` back as `If-Match`.

## The pattern

1. Read the page or its blocks. The answer has an `ETag` header.
2. Change it (PUT the page, or add, change, move or remove a block) with `If-Match: <that ETag>`.
3. If the page changed since you read it, the write is refused with `412 precondition_failed`. Read it again, apply your change to what is there now, and save.

```js tab="JavaScript"
async function setHeading(siteId, heading) {
  for (;;) {
    const page = await fetch(`https://api.unvop.com/v1/sites/${siteId}/pages/index`, { headers });
    const etag = page.headers.get('ETag');
    const { blocks } = await page.json();
    const res = await fetch(`https://api.unvop.com/v1/sites/${siteId}/pages/index/blocks/${blocks[0].id}`, {
      method: 'PATCH',
      headers: { ...headers, 'Content-Type': 'application/json', 'If-Match': etag },
      body: JSON.stringify({ props: { heading } }),
    });
    if (res.status !== 412) return res.json();
  }
}
```

```python tab="Python"
def set_heading(site_id, heading):
    while True:
        page = requests.get(f"https://api.unvop.com/v1/sites/{site_id}/pages/index", headers=headers)
        etag = page.headers["ETag"]
        block = page.json()["blocks"][0]
        res = requests.patch(
            f"https://api.unvop.com/v1/sites/{site_id}/pages/index/blocks/{block['id']}",
            headers={**headers, "If-Match": etag},
            json={"props": {"heading": heading}},
        )
        if res.status_code != 412:
            return res.json()
```

Without `If-Match` the write goes ahead, last write wins. That is fine for a script that owns a page; use `If-Match` whenever people might be editing too.

## Where it applies

Page reads (`GET …/pages/{page}` and `GET …/pages/{page}/blocks`) return an ETag. Page writes (`PUT …/pages/{page}` and every block change: add, change, move and remove) accept `If-Match`. The design stylesheet works the same way with a `version` field instead: send the `version` you read with `PUT …/design/styles/{file}` and the save is refused if the part changed since.
