# Idempotent Requests

> Retry a POST safely with an Idempotency-Key, so a study or a report is never started twice.

Source: https://imario.ai/docs/api/idempotency

## Why

A request can fail on the way back: the study started, but the connection dropped before you saw the answer. Sending the request again would start a second study and charge twice. An `Idempotency-Key` header prevents that.

## How

Send a key you choose, unique to the operation, on any POST:

```bash
curl https://api.imario.ai/v1/studies \
  -H "Authorization: Bearer $IMARIO_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: 0b8f6a52-3c1d-4e7f-9a2b-5c6d7e8f9a0b" \
  -d '{"kind": "open_question", "question": "What would make you switch banks?", "audience_ids": ["AUDIENCE_ID"]}'
```

A UUID per operation works well. The key is 1 to 255 characters; spaces around it are ignored, and an empty or longer key is refused with 400 `idempotency_key_invalid`. Keep it with the job that sends the request, so a retry of the same job reuses it.

## What happens on a retry

| You send | You get |
|---|---|
| The same key, the same path and body, after the first request finished | The first answer again, status and body, with the header `Idempotent-Replayed: true`. Nothing runs twice |
| The same key while the first request is still running | 409 `request_in_progress`. Retry after a few seconds |
| The same key with a different body or path | 409 `idempotency_key_reused`. Use a new key for a new request. The body is compared byte for byte, so resend the bytes you sent, not a copy serialised again |

Keys are kept for 24 hours and belong to the API key that sent them: two API keys can use the same `Idempotency-Key` without clashing.

An answer with a 5xx status is not kept, since the work may not have happened: a retry with the same key runs the request again. Neither is a 402, 409 or 429: they depend on the moment (the balance or the daily limit, a study still running, the rate limit), so after you add credits, wait, or wait out `Retry-After`, a retry with the same key runs the request again. Any other 4xx answer is kept and replayed, because sending the same request again would fail the same way: fix the request and send it with a new key.

A request still running after two minutes no longer holds its key, and a retry then runs it again. A replayed answer does not count against the [rate limits](https://imario.ai/docs/api/rate-limits).

GET, PATCH and DELETE requests do not need a key: sending them twice has the same effect as sending them once.
