> The index of all pages is at https://docs.afffast.com/llms.txt.

# Idempotency

Repeat a POST request safely with an Idempotency-Key.

A network error can leave you not knowing if a `POST` request worked. If you send it again, you can make a duplicate. Send an `Idempotency-Key` header to avoid this.

```bash
curl -X POST https://api.afffast.com/v1/sites \
  -H "Authorization: Bearer $AFFFAST_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: 5f0c2a0e-6b1d-4a3e-9c1f-0d2b7e8a9c11" \
  -d '{ "name": "Blog" }'
```

## Rules

- The header is optional. It is for `POST` requests. A `GET`, `PATCH` or `DELETE` request is safe to repeat without it.
- The key has 1 to 256 printable characters. Use a random value, for example a UUID. A key that is not valid gets [`idempotency_key_invalid`](https://docs.afffast.com/errors/idempotency-key-invalid.md).
- The API runs the first request with a key. It stores the response, also an error response (a `5xx` too). It keeps the response for **24 hours**.
- The same key with the same method, path and body returns the stored response. The response has the header `Idempotent-Replayed: true`. It has the original body and a new `Request-Id`.
- The same key with a different method, path or body returns `409` [`idempotency_key_reused`](https://docs.afffast.com/errors/idempotency-key-reused.md).
- The same key while the first request still runs returns `409` [`idempotent_request_in_progress`](https://docs.afffast.com/errors/idempotent-request-in-progress.md). Wait, and send the request again.
- A key is valid for one API key. Two API keys can use the same value without a conflict.

## Responses that have a secret

A few responses have a secret that the API shows one time: a new webhook endpoint (`secret`), a rotated secret and a new API key. The API does **not** store these responses. A repeat request runs again and makes a new object or a new secret.

## Good practice

1. Make a new key for each new action.
2. Save the key before you send the request.
3. When a request fails or times out, send it again with the **same** key and the same body.
4. After an error response that you got, use a **new** key if you want the API to try again. The API replays the stored error for the old key.
