Get started
API conventions

Conditional writes

Conditional writes

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 need a session token minted for a member, as act as a member shows.

# 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_SESSION_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_SESSION_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_SESSION_TOKEN" \
  -H "Idempotency-Key: $(uuidgen)"
Response to the stale write
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.

Next steps

Last updated