Glossary · API testing
Idempotency
Also called: idempotent, idempotent request, idempotent requests, Idempotency-Key
Definition
The property that sending the same request once or many times leaves the server in the same state. GET, PUT and DELETE are idempotent, POST is not.
An operation is idempotent if repeating it has the same effect on the server as doing it once. It matters because networks fail: a client that times out does not know whether its request arrived, and retrying is only safe when the request is idempotent. Idempotency is about server state, not about getting an identical response every time.
Which HTTP methods are idempotent
| Method | Idempotent | Safe (no side effects) |
|---|---|---|
GET, HEAD, OPTIONS |
Yes | Yes |
PUT |
Yes | No |
DELETE |
Yes | No |
POST |
No | No |
PATCH |
Not guaranteed | No |
DELETE /orders/42 sent twice might return 204 and then 404. The responses differ, but the state is the same: the order is gone. That is still idempotent.
PUT versus PATCH
PUT replaces the whole resource with the body you send. Sending PUT /users/7 with {"name": "Ada", "plan": "pro"} three times leaves the same user each time, so it is idempotent.
PATCH applies a change, and whether it is idempotent depends on the change. {"plan": "pro"} sets a value and is idempotent in practice. An operation like “increment loginCount by 1”, or a JSON Patch add to an array, gives a different result each time, so PATCH as a method is not guaranteed to be idempotent.
Making POST safe to retry
Payment and ordering APIs often accept an idempotency key: the client generates a unique value and sends it in a header such as Idempotency-Key. The server stores the result of the first request with that key and returns the same result for any repeat, instead of creating a second order.
POST /payments HTTP/1.1
Content-Type: application/json
Idempotency-Key: 6f1c2a9e-3b7d-4f0a-9c2e-1d5b8a7e4f60
{"amount": 4999, "currency": "EUR"}
How to test it
- Send the same
PUTorDELETEtwice and assert the resource state, not just the status code. - Send the same
POSTwith the same idempotency key twice. Expect one resource and the same response body. - Reuse a key with a different body. A well-designed API rejects this rather than silently returning the old result.
- Fire duplicate requests concurrently. Race conditions are where idempotency handling usually breaks.