# Conditional writes

> Canonical URL: https://docs.mountaya.com/en/apis/conventions/conditional-writes/
> Last updated: 2026-11-27
> Rules for agents: https://docs.mountaya.com/llms.txt#rules-for-agents

Send a resource's ETag back as If-Match, so a write lands only if nobody changed the resource since you read it.

Itineraries, zones, collections, and the other resources you edit carry an `etag`. Send it back as `If-Match`, and the write lands only if nobody changed the resource since you read it. Otherwise it is refused with `412 Precondition Failed`, and nothing changes.

The samples below create a collection, update it under its tag, then try the old tag again. They read a session token minted for a member from `MOUNTAYA_MEMBER_TOKEN`, as [act as a member](https://docs.mountaya.com/en/authentication.md#acting-as-a-member) shows.

**cURL**

```bash
# Create a collection, and keep its id and its tag.
CREATED=$(curl -s -X POST https://api.mountaya.com/v1/collections \
  -H "X-API-Key: $MOUNTAYA_PUBLISHABLE_KEY" \
  -H "X-Session-Token: $MOUNTAYA_MEMBER_TOKEN" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Content-Type: application/json" \
  -d '{"name": "Docs conditional writes", "is_private": true}')
COLLECTION_ID=$(echo "$CREATED" | jq -r .data.id)
ETAG=$(echo "$CREATED" | jq -r .data.etag)

# Update it under that tag, twice. The second write is stale and answers 412.
for attempt in 1 2; do
  curl -s -o /dev/null -w "%{http_code}\n" -X PATCH "https://api.mountaya.com/v1/collections/$COLLECTION_ID" \
    -H "X-API-Key: $MOUNTAYA_PUBLISHABLE_KEY" \
    -H "X-Session-Token: $MOUNTAYA_MEMBER_TOKEN" \
    -H "Idempotency-Key: $(uuidgen)" \
    -H "If-Match: $ETAG" \
    -H "Content-Type: application/json" \
    -d '{"description": "Multi-day hikes around Mont Blanc."}'
done

curl -s -X DELETE "https://api.mountaya.com/v1/collections/$COLLECTION_ID" \
  -H "X-API-Key: $MOUNTAYA_PUBLISHABLE_KEY" \
  -H "X-Session-Token: $MOUNTAYA_MEMBER_TOKEN" \
  -H "Idempotency-Key: $(uuidgen)"
```

**TypeScript**

```typescript
import { Mountaya, MountayaPreconditionFailedError } from "@mountaya/client";

const mountaya = new Mountaya({
  credential: {
    publishableKey: process.env.MOUNTAYA_PUBLISHABLE_KEY ?? "",
    sessionToken: process.env.MOUNTAYA_MEMBER_TOKEN ?? "",
  },
});

const { data: collection } = await mountaya.studio.collections.postCollection({
  body: { is_private: true, name: "Docs conditional writes" },
});

// Lands only if nobody changed the collection since it was read.
const { data: updated } = await mountaya.studio.collections.patchCollection({
  body: { description: "Multi-day hikes around Mont Blanc." },
  collection_id: collection.id,
  ifMatch: collection.etag,
});

try {
  // The first tag is stale now, so this write is refused.
  await mountaya.studio.collections.patchCollection({
    body: { description: "A stale edit." },
    collection_id: collection.id,
    ifMatch: collection.etag,
  });
} catch (error) {
  if (!(error instanceof MountayaPreconditionFailedError)) {
    throw error;
  }
  console.log(error.status, "current tag:", error.etag);
}

await mountaya.studio.collections.deleteCollection({ collection_id: collection.id, ifMatch: updated.etag });
```

**Python**

```python
import os
import uuid

import requests

collection = requests.post(
    "https://api.mountaya.com/v1/collections",
    headers={
        "X-API-Key": os.environ["MOUNTAYA_PUBLISHABLE_KEY"],
        "X-Session-Token": os.environ["MOUNTAYA_MEMBER_TOKEN"],
        "Idempotency-Key": str(uuid.uuid4()),
    },
    json={"name": "Docs conditional writes", "is_private": True},
    timeout=30,
).json()["data"]

# Update it under its tag, twice. The second write is stale and answers 412.
for attempt in range(2):
    answer = requests.patch(
        f"https://api.mountaya.com/v1/collections/{collection['id']}",
        headers={
            "X-API-Key": os.environ["MOUNTAYA_PUBLISHABLE_KEY"],
            "X-Session-Token": os.environ["MOUNTAYA_MEMBER_TOKEN"],
            "Idempotency-Key": str(uuid.uuid4()),
            "If-Match": collection["etag"],
        },
        json={"description": "Multi-day hikes around Mont Blanc."},
        timeout=30,
    )
    print(answer.status_code, answer.headers["ETag"])

requests.delete(
    f"https://api.mountaya.com/v1/collections/{collection['id']}",
    headers={
        "X-API-Key": os.environ["MOUNTAYA_PUBLISHABLE_KEY"],
        "X-Session-Token": os.environ["MOUNTAYA_MEMBER_TOKEN"],
        "Idempotency-Key": str(uuid.uuid4()),
    },
    timeout=30,
).raise_for_status()
```

**Response to the stale write**

```http
HTTP/1.1 412 Precondition Failed
Content-Type: application/json
Etag: "d2"

{"errors":[{"message":"The resource changed since it was read.","extensions":{"code":"PRECONDITION_FAILED"}}]}
```

On a `412`, read the resource again, decide whether your change still applies, and send it with the new tag. The `ETag` header of the refusal names the current version. Leave out `If-Match`, and the last write wins.

- Nine resources carry an `etag`: `Itinerary`, `ItineraryWithDetails`, `Zone`, `Collection`, `Organization`, `OrganizationSettings`, `PublishableKey`, `AiProviderConfig`, and `WebhookEndpoint`. Every answer that returns one carries the same value in an `ETag` header. It is an opaque tag in double quotes, such as `"d42"`, that moves whenever what that read returns moves. Compare it whole, and never parse it.
- A webhook endpoint's tag moves with its configuration and its status, never with its health: a delivery failing or succeeding again moves `failing_since` and leaves the tag as it is, so a change sent with it is never refused for a delivery made meanwhile.
- `If-Match` is taken by the `PATCH` and `DELETE` of each of those resources, by every write to an itinerary's segments, segment groups, waypoints, and publication, by the publication of a zone (`POST` and `DELETE /v1/zones/{zone_id}/publication`), and by every write to what a collection holds. It names one tag, or `*` for any version. A list of tags or a weak `W/` tag is a `400`.
- When the resource has moved on, the write is refused with `412 Precondition Failed`, coded `PRECONDITION_FAILED`. Nothing is changed, and the answer's `ETag` names the current version. Resending the same tag is refused the same way.
- The condition is asked last: a stale tag is answered only for a write that would otherwise go through. A resource you cannot see answers `404`, a role that may not make the write `403`, a refused body `400`, a conflict `409`, and a ceiling its `LIMIT_REACHED`, each before the tag is compared. So a tag never tells a caller more than a read would.
- An itinerary's tag covers what lies under it. Its read returns its segments, waypoints, and publication, so a write to any of them moves the itinerary's tag.
- An organization's settings carry their own tag. Renaming the organization never refuses a change to its settings, and the reverse.
- Omit `If-Match` and the last write wins. The condition is yours to ask for, never imposed.
- `If-Match` is not part of what the `Idempotency-Key` compares, so a write sent again with a fresh tag after a `412` takes a new key: under the old one, it is answered the `412` again.
- In TypeScript, pass `ifMatch` on the write; a `412` raises `MountayaPreconditionFailedError`, whose `etag` is the tag the resource carries now. The client never retries a `412`.

## Next steps

- [Idempotency](https://docs.mountaya.com/en/apis/conventions/idempotency.md): Retry a write without making it twice.
- [Errors](https://docs.mountaya.com/en/apis/conventions/errors.md): Conflicts, stale writes, and the other refusals.
