# Idempotency and deduplication (https://eulabel.eu/docs/knowledge-base/guides/idempotency-and-deduplication)

> Fetch the complete documentation index at: https://eulabel.eu/docs/llms.txt
> Use this file to discover all available pages before exploring further.
> Full content: https://eulabel.eu/docs/llms-full.txt
> Append .md to any page URL for markdown, or send Accept: text/markdown.



`POST /v1/passports` is safe to repeat, with one exception: after a withdrawal, a repeat publishes again. The GTIN finds the product, your data merges into its passport, and identical data changes nothing. For other `POST` calls, send an [`Idempotency-Key`](#retry-any-post-with-an-idempotency-key).

**Video: Create or enrich: 201, 200, draft and published** (https://pub-7ea90ccdf0f545b3ad4613d72e450782.r2.dev/idempotency.mp4). A passport is created as a draft, the same call returns 200, and more data publishes it with a 201.

## How one call is decided
```mermaid
flowchart TD
  A[Merge your data]:::blue --> B{Same as stored?}:::blue
  B -->|Yes| C[200]:::gray
  B -->|No| D[201]:::green
```

| Current passport | Your call | Status | Result |
| --- | --- | --- | --- |
| None | Any data | `201` | Version 1, draft or published. |
| Any | Same data, same outcome | `200` | Nothing changes. `updatedAt` stays the same. |
| Draft | New data, still incomplete | `201` | The draft is updated. `version` stays the same. |
| Draft | Data that completes it | `201` | Published as a new version. |
| Published | New compliant data | `201` | New published version. The old one is archived. |
| Published | `publish: false`, or data that breaks compliance | `201` | A draft sits above the live version. The public still sees the live one. |
| Withdrawn | Any compliant call, even an exact replay | `201` | **Published again** as a new version. |
| Withdrawn | `publish: false` | `201` | A draft. The passport stays offline. |

> **Warning**
> **A scheduled sync undoes a withdrawal.** Withdrawing takes the live version away, so a replay no longer matches what is stored. It returns `201`, not `200`, and the passport goes live again. Keep withdrawn products out of the sync, or send `publish: false` on every call for them. One call without it publishes.

> **Warning**
> `201` doesn't always mean a new passport, and `compliance.status: compliant` doesn't mean live. Check `status` for `published`, because `publish: false` keeps a compliant passport as a draft.

## Try it: send the same call twice
The first call stores a draft and the second changes nothing. `projectId` picks the sector, so use one of your own projects.

#### cURL


```bash
BODY='{
  "gtin": "5609750337814",
  "name": "Quinta Demo Reserva 2022",
  "brand": "Quinta Demo",
  "projectId": "50599d2c-556a-4cf7-ba16-8d3bcf008492",
  "data": { "ingredients": ["Grapes", "Preservative: sulphites"] }
}'

for attempt in 1 2; do
  curl -s -o /dev/null -w "%{http_code}\n" -X POST https://api.eulabel.eu/v1/passports \
    -H "Authorization: Bearer $EULABEL_API_KEY" \
    -H "Content-Type: application/json" \
    -d "$BODY"
done
```

#### JavaScript


```javascript
const send = (payload) =>
  fetch('https://api.eulabel.eu/v1/passports', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.EULABEL_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(payload),
  });

const payload = {
  gtin: '5609750337814',
  name: 'Quinta Demo Reserva 2022',
  brand: 'Quinta Demo',
  projectId: '50599d2c-556a-4cf7-ba16-8d3bcf008492',
  data: { ingredients: ['Grapes', 'Preservative: sulphites'] },
};

for (const attempt of [1, 2]) {
  const res = await send(payload);
  if (!res.ok) throw new Error((await res.json()).error.message);
  console.log(res.status);
}
```

#### Python


```python
import os
import requests

payload = {
    "gtin": "5609750337814",
    "name": "Quinta Demo Reserva 2022",
    "brand": "Quinta Demo",
    "projectId": "50599d2c-556a-4cf7-ba16-8d3bcf008492",
    "data": {"ingredients": ["Grapes", "Preservative: sulphites"]},
}

for attempt in (1, 2):
    res = requests.post(
        "https://api.eulabel.eu/v1/passports",
        headers={"Authorization": f"Bearer {os.environ['EULABEL_API_KEY']}"},
        json=payload,
    )
    res.raise_for_status()
    print(res.status_code)
```


```text
201
200
```

Send the remaining fields for the same GTIN, leaving out what is already stored. The data merges, and once it is compliant the passport publishes as a new version with `201`.

## How data merges
| Incoming value | Result |
| --- | --- |
| New field | Added. |
| Object over an object | Merged field by field. |
| Single value | Replaces the old value. |
| Array | Replaces the whole array. It is not appended. |
| `null` | Stored as `null`. A required field set to `null` counts as missing. |

## Retry any POST with an Idempotency-Key
Send an `Idempotency-Key` header with a new UUID for each operation, and the same key on its retries. The first `2xx` response is stored for 24 hours. A retry with the same key, method, path, query and body gets that response back, with `Idempotent-Replayed: true`, and nothing runs twice. Keys belong to your organization, so two of your API keys share them.

#### cURL


```bash
KEY=$(uuidgen)
for attempt in 1 2; do
  curl -s -D - -o /dev/null -X POST https://api.eulabel.eu/v1/projects \
    -H "Authorization: Bearer $EULABEL_API_KEY" \
    -H "Content-Type: application/json" \
    -H "Idempotency-Key: $KEY" \
    -d '{"name": "Quinta Demo Whites", "type": "wine"}' \
    | grep -iE "^HTTP|^idempotent-replayed"
done
```

#### JavaScript


```javascript
const idempotencyKey = crypto.randomUUID();
const createProject = () =>
  fetch('https://api.eulabel.eu/v1/projects', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.EULABEL_API_KEY}`,
      'Content-Type': 'application/json',
      'Idempotency-Key': idempotencyKey,
    },
    body: JSON.stringify({ name: 'Quinta Demo Whites', type: 'wine' }),
  });

for (const attempt of [1, 2]) {
  const res = await createProject();
  const body = await res.json();
  if (!res.ok) throw new Error(`${body.error.code}: ${body.error.message} (${body.error.requestId})`);
  console.log(res.status, res.headers.get('Idempotent-Replayed'), body.projectId);
}
```


```text
HTTP/2 201
idempotent-replayed: false
HTTP/2 201
idempotent-replayed: true
```

Both responses carry the same `projectId`, and only one project exists.

| Response | Cause | What to do |
| --- | --- | --- |
| `2xx`, `Idempotent-Replayed: true` | A retry of a request that already succeeded. | Use the response. Nothing ran again. |
| `409 idempotency_request_in_progress` | The first request with this key is still running. | Wait for `Retry-After`, then retry with the same key. |
| `422 idempotency_key_reused` | The key was used within 24 hours for a different request. | Use a new key for each new operation. |
| `400 invalid_idempotency_key` | The key is empty, longer than 255 characters, or has spaces or non-ASCII characters. | Send a UUID. |
| `400 idempotency_not_supported` | `POST /v1/access-grants` returns a token once and never stores it. | Send it without the header. List grants before retrying a failed call. |

Error responses aren't stored. A retry after a `4xx` or `5xx` runs again, because the failed request changed nothing. The header works on every `POST` except `POST /v1/access-grants`, and other methods ignore it.

## Which calls are safe to repeat without a key
Without an `Idempotency-Key`, each call behaves as follows when repeated.

| Call | Repeating it |
| --- | --- |
| `POST /v1/passports` | Safe. Returns `200` when nothing changed. After a withdrawal it publishes again. |
| `POST /v1/products/{productId}/items` | Safe. The same serial number updates the item and returns `200`. |
| `POST /v1/company-prefixes` | Safe. Returns the existing claim with `200`. |
| `POST /v1/products` | Fails. Use `POST /v1/passports`, or look up the GTIN first. |
| `POST /v1/products/import` | Creates only the new lines and lists repeats in `errors`. Returns `201` if any line is new, otherwise `422`. |
| `POST /v1/products/{productId}/suppliers` | Fails if the supplier is already linked, in any role. |
| `POST /v1/domains` | Fails for the same domain. |
| `POST /v1/products/{productId}/passport/withdraw` | Returns `409 not_published`. |
| `POST .../items/{serial}/events` | Records a second event. A repeated status change returns `422`. |
| `POST /v1/access-grants` | Issues a second grant with a new token. |

See [error handling](https://eulabel.eu/docs/knowledge-base/guides/error-handling) for the status codes of the calls that fail.

