Safe methods (GET, HEAD, OPTIONS) do not change state, and idempotent ones (those plus PUT and DELETE) leave the same state after N calls as after one. PUT replaces a resource fully and PATCH changes a part, so PATCH's idempotency depends on the operation ("set" or "add"). Idempotency concerns state, not the response: a repeated DELETE may return 404. POST is not idempotent, so payments need an Idempotency-Key.
API · Methods
A client repeated a request after a timeout. Will a second record be created or not?
A mobile client sent a request, the network dropped and the app retried it automatically. For GET that costs nothing. For POST /orders it can be a second order, and for DELETE a different response to the same request. The answer to "what happens on a retry" depends on the method, and it is exactly what an interviewer asks for.
This lesson sorts the methods by two properties, safety and idempotency, explains why they are defined that way and shows how to check them in a test.
How it works
RFC 9110 describes methods through their semantics, not through what a particular server does. It is a contract between the client, proxies and caches: they decide from it what may be cached, prefetched and retried automatically.
GET reads a resource, HEAD does the same without the body, OPTIONS asks about capabilities (the CORS preflight is an OPTIONS too).
POST creates a resource or triggers an action, PUT replaces a resource fully, PATCH changes a part, DELETE removes.
A safe method is not expected to change state: GET, HEAD, OPTIONS (and TRACE). That is why a browser or a crawler may call them without asking. An idempotent method has the same effect on the server after one call and after N: all safe methods plus PUT and DELETE. POST is not idempotent, and PATCH is not guaranteed to be (RFC 5789).
Safe, idempotent and all the others
Figure 1. Every safe method is idempotent but not the other way round: PUT and DELETE change state, yet a repeat adds nothing. POST and PATCH stand outside the circles.
Note that idempotency concerns the server state, not the response. A repeated DELETE may give 404 instead of 204 and the method is still idempotent, because the resource is gone either way. Clients and proxies need it to retry safely when a response did not arrive: it is unknown whether the server executed the request.
Example: a retry after a timeout
There is a user 7. The client repeats PUT first, since the body fully describes the final state:
PUT /v1/users/7 HTTP/1.1
Content-Type: application/json
{ "firstName": "Olena", "lastName": "Koval", "nickname": "olena" }
HTTP/1.1 200 OK (the second identical PUT: 200 again, same state)
The second PUT changes nothing, so a retry is safe. The same goes for DELETE: the state after a repeat is the same, only the response changes.
curl -i -X DELETE "$BASE/v1/orders/17" -H "Authorization: Bearer $TOKEN"# HTTP/1.1 204 No Content
curl -i -X DELETE "$BASE/v1/orders/17" -H "Authorization: Bearer $TOKEN"# HTTP/1.1 404 Not Found (the response differs, the server state is the same)
Now POST. It says "create something new" and the server cannot know this is the same intent. A test that proves it:
import { test, expect } from'@playwright/test';
test('PUT twice leaves one state, POST twice leaves two', async ({ request }) => {
const body = { firstName: 'Olena', lastName: 'Koval', nickname: 'olena' };
await request.put('/v1/users/7', { data: body });
const first = await (await request.get('/v1/users/7')).json();
await request.put('/v1/users/7', { data: body });
const second = await (await request.get('/v1/users/7')).json();
expect(second).toEqual(first);
const a = await request.post('/v1/orders', { data: { sku: 'A1', qty: 1 } });
const b = await request.post('/v1/orders', { data: { sku: 'A1', qty: 1 } });
expect((await a.json()).id).not.toBe((await b.json()).id); // two orders
});
The first steps compare the state before and after a repeat, the last one shows that two POSTs create two orders. That is not a bug: POST is designed that way. The bug is a payment or an order duplicated where the client has a right to retry (see Idempotency-Key in the fintech lesson).
PUT versus PATCH and the limits of the rule
PUT sends the full representation, so a repeat gives the same state. PATCH describes a change, and its nature depends on the format. "Set tier = gold" is idempotent, while "append a tag to the list" or "increase the counter by 1" is not. That is why the table says "not guaranteed", not "no".
A repeated POST and PUT
PUT /users/7 twice
The same final state. The client may retry when it got no response.
POST /orders twice
Two new orders unless the server tells a retry from a new intent.
Figure 2. Both behaviours are correct if they match the method. A defect appears when a POST in a financial operation is retried without an idempotency key.
Other limits: safety is a commitment of the service, not a guarantee. If GET /orders/17/cancel cancels an order, that is a defect: a browser prefetch or a cache may call it. Idempotency does not protect against races either: two different PUTs from two clients can overwrite each other (that is what If-Match and ETag are for). A body in GET and DELETE has no defined semantics (RFC 9110), so do not rely on it.
Common mistakes
"Idempotent" means "the same response". No: a 404 on a repeated DELETE is fine, and a test should not fail on a different status if the contract allows it.
Treating PATCH as idempotent. Then a test repeats a "+1" operation and is surprised by the difference.
Writing a GET that changes data. A cache and a prefetch will fire it without the user's intent.
Leaving POST unprotected against a repeat in a payment flow.
Check yourself
A client repeated DELETE /orders/17 and got 404. Is that a bug?
Answer
No, if the contract allows it. The server state is the same: the order is gone. Idempotency describes state, not the response code. It would be a bug if the repeat deleted something else or returned 500.
Why is it safe to repeat PUT but not POST?
Answer
PUT names the resource address and the full state: after the second call the resource is the same. POST means "create", and the server cannot know it is a retry of the same intent, so it creates another record. Idempotency-Key is the protection.
Is PATCH {"views": 1} idempotent?
Answer
It depends on the semantics. If it means "set views = 1", yes. If it is an increment "+1", no. The contract has to say so, and a test should repeat the request and compare the state through GET.
Related lessons: “The methods table”, “PUT vs PATCH and Idempotency-Key in fintech”, “Timeouts, retries and idempotency keys”.
In an interview.Junior: GET reads, POST creates, PUT replaces fully, PATCH changes a part, DELETE removes. Safe GET, HEAD, OPTIONS do not change data, idempotent GET, PUT, DELETE give the same state after several calls, POST is not idempotent. Middle/Senior: Idempotency is about state, not the response: a repeated DELETE may give 404. Automatic retries of clients and proxies rest on it. For POST in payments I check Idempotency-Key, for PATCH I clarify whether the operation is "set" or "add", and I treat a GET that changes state as a defect.
The methods table
GET, HEAD and OPTIONS are safe and idempotent, PUT and DELETE are idempotent, POST is not, and PATCH is not guaranteed. Typical success: GET 200, POST 201 with Location or 202 for asynchronous work, PUT 200 or 204, DELETE 204. An unsupported method should return 405 with an Allow header, not 404 or 500. The table gives typical expectations; the reference is the service contract.
API · Methods
Which code to expect from PUT and which from DELETE? A table worth knowing by heart.
Test cases for an endpoint begin with "which response counts as correct". Each method has settled expectations: what to return, whether there is a body, whether it can be repeated, whether it is cached. Knowing this table saves time when reviewing documentation and catches mistakes before the first run.
The table
Method
Purpose
Request body
Safe
Idempotent
Typical success
GET
Get a resource or a list
No
Yes
Yes
200
HEAD
Like GET, without the body
No
Yes
Yes
200
OPTIONS
Capabilities, CORS preflight
No
Yes
Yes
200 or 204
POST
Create a resource or run an action
Yes
No
No
201 or 200, 202
PUT
Replace a resource fully
Yes
No
Yes
200 or 204 (201 if created)
PATCH
Change some fields
Yes
No
Not guaranteed
200 or 204
DELETE
Remove a resource
Usually no
No
Yes
204, 200 or 202
Why the codes are what they are
A success code is not arbitrary, it tells the client what happened. 201 Created says a new resource appeared, and a Location with its address goes along. 204 No Content says "done, no body": typical for DELETE and PUT, which have nothing to return. 202 Accepted says "accepted, processing continues": the answer to a long operation, the client gets the result later. 200 is kept for cases where the response has a body with the result.
So the same action in different APIs may correctly give different codes. A PUT to an existing resource gives 200 or 204, and a PUT to a new address, where the API allows it, gives 201. That is not a defect as long as the code matches the documentation and is the same across the service's endpoints.
Example: checking the table on a live API
HEAD is useful to check existence and size of a file without downloading it, and OPTIONS shows what a resource supports:
curl -I "$BASE/v1/files/9" -H "Authorization: Bearer $TOKEN"# 200, Content-Length: 1048576, no body
curl -i -X OPTIONS "$BASE/v1/orders"# 204, Allow: GET, POST, OPTIONS
Two tests that take a few minutes to add to a suite:
test('HEAD matches GET headers and has no body', async ({ request }) => {
const get = await request.get('/v1/files/9');
const head = await request.head('/v1/files/9');
expect(head.status()).toBe(get.status());
expect(head.headers()['content-length']).toBe(get.headers()['content-length']);
expect((await head.body()).length).toBe(0);
});
test('unsupported method gives 405 with Allow', async ({ request }) => {
const res = await request.delete('/v1/orders');
expect(res.status()).toBe(405);
expect(res.headers()['allow']).toContain('GET');
});
The first checks the HEAD contract: the same status and headers as GET, but no body. The second catches a classic mistake where the server returns 404 or 500 for an unsupported method instead of 405 Method Not Allowed with an Allow header. RFC 9110 requires this header in a 405.
Idempotency and the response
Server state
After the first and the second DELETE the resource is gone. That is what idempotency is about.
Response code
204 the first time, 404 the second. That is allowed: the code may differ, the state may not.
Figure 1. Two different things that are easy to mix up: idempotency belongs to the state, not to the code.
Limits of the table
The table describes typical expectations. A real API may return 200 with a body on DELETE (the deleted object) or 202 for an asynchronous delete. The reference is the service contract.
The "idempotent" mark is the intent of the method too: a server can implement PUT so that it is not. A test checks exactly that.
Not every API supports HEAD and OPTIONS. If a method is not implemented, we expect 405, not 500.
Some caches and clients cache only GET and HEAD. Responses to POST are cached rarely, only with explicit headers.
Common mistakes
Expecting 200 for everything. A test that checks only "success" misses a 201 without Location or a 204 with a body.
Comparing a DELETE repeat by code. It may differ, so the state is compared through GET.
Demanding a body from HEAD. By definition there is none, and the headers should match GET.
Mixing "safe" and "idempotent". PUT and DELETE change state, so they are unsafe, yet idempotent.
Check yourself
Which code to expect from POST /orders and what else to check in the response?
Answer
201 Created (200 or 202 depending on the contract). I also check Location or the id in the body, then a GET at that address: the resource must exist.
The server returns 404 for DELETE /orders (a collection). Is that right?
Answer
No, 405 Method Not Allowed with an Allow header would be more precise: the resource exists but the method is not supported for it. 404 misleads, and 500 is a bug.
Why is PUT called unsafe but idempotent?
Answer
A safe method does not change state. PUT does, so it is unsafe. Idempotency says a repeat of the same PUT changes nothing beyond the first. These are two independent properties.
Related lessons: “HTTP methods, idempotency, PUT vs PATCH”, “Testing checklist by method: what to check for GET, POST, PUT, PATCH, DELETE”, “401 vs 403, 400 vs 422, 500 vs 503”.
In an interview.Junior: GET, HEAD, OPTIONS are safe and idempotent, PUT and DELETE are idempotent, POST is not, PATCH is not guaranteed. Success: GET 200, POST 201, DELETE 204. Middle/Senior: A success code carries meaning: 201 with Location, 204 without a body, 202 for asynchronous processing. An unsupported method must give 405 with Allow. Idempotency belongs to the state, so a DELETE repeat with 404 is fine, and PATCH depends on the operation. I use the table as a starting grid and take the reference from the service contract.
PUT vs PATCH and Idempotency-Key in fintech
PUT replaces a resource fully and PATCH changes only the fields sent, so a field missing from PUT must not survive. A retried POST in payments is protected by Idempotency-Key: the client adds a unique key, and on a retry the server returns the stored response without acting again. The same key with a different body is rejected (the draft recommends 422). Parallel requests with one key are tested.
API · Methods
A user clicked "Pay" twice. How to guarantee the money is charged once?
Two scenarios that reach production too often. In the first, a PUT without one field silently wipes it in the database, because the developer implemented "replace" as "update". In the second, a retry of a payment request after a timeout charges twice. Both are testable in minutes if you know what to compare.
PUT and PATCH: replace or change
PUT says "here is the full state of the resource". Anything missing from the body is considered absent. PATCH says "here is what to change". The rest stays. By the specification, a PATCH document must describe a change, and its format is a separate agreement: most often JSON Merge Patch (RFC 7396, application/merge-patch+json) or JSON Patch (RFC 6902, application/json-patch+json).
// current state of the resource
{ "id": 7, "firstName": "Olena", "nickname": "olena", "city": "Kyiv" }
// PUT body (no "city") // PATCH body (no "city")
{ "firstName": "Olena", { "nickname": "ol" }
"nickname": "ol" }
// result: city is gone or // result: city stays "Kyiv"
// reset to a default
The same request without the "city" field
PUT without city
It is a full replace. The field disappears or is reset to a default.
PATCH without city
The field is not touched. State changes only where the body has a value.
Figure 1. The same data gives a different result. That is not a mistake as long as the contract says so.
A test for PUT checks the state through GET, not the response:
test('PUT without a field: documented replace', async ({ request }) => {
await request.put('/v1/users/7', {
data: { firstName: 'Olena', nickname: 'ol' }, // "city" is missing
});
const user = await (await request.get('/v1/users/7')).json();
expect(user.nickname).toBe('ol');
// contract says PUT is a full replace, so city must be resetexpect(user.city ?? null).toBeNull();
});
If the documentation says "PUT replaces the resource" but city stayed, the API behaves like PATCH, and that is a deviation from the contract. If the field is required, a PUT without it should give 400 or 422, not silently wipe it.
PATCH idempotency is subtler. Merge Patch { "tier": "gold" } is idempotent in practice. A JSON Patch with an add at the end of an array, or a counter increment, is not:
PATCH /v1/accounts/42 HTTP/1.1
Content-Type: application/json-patch+json
[{ "op": "add", "path": "/tags/-", "value": "vip" }]
# repeated: "vip" is appended again, so this PATCH is not idempotent
PATCH /v1/accounts/42 HTTP/1.1
Content-Type: application/merge-patch+json
{ "tier": "gold" }
# repeated: the same state, idempotent in practice
Idempotency-Key: how not to charge twice
POST is not idempotent, and in fintech it is repeated all the time: a timeout, a dropped network, a second click, a library retry. The client does not know whether the server executed the request. The solution: the client generates a unique key (a UUID v4) and puts it in a header. The server stores the pair "key, result" and on a repeat returns the saved response without performing the action again. The header is described in an IETF draft (Idempotency-Key) and is widely used by payment APIs (Stripe and others).
POST /v1/transfers HTTP/1.1
Idempotency-Key: 7f3c9a10-5d2e-4b8a-9c11-0e6f2a7b1d34
Content-Type: application/json
{ "toAccount": "UA21...", "amount": 150.00, "currency": "UAH" }
HTTP/1.1 201 Created
Location: /v1/transfers/tr_91
The idempotency key at work
Figure 2. The response got lost, but the client knows the key and may retry. The server sees K1, returns the stored result and does not create a second payment.
The same key, a different body
Typical
Request POST /v1/transfers, Idempotency-Key: 7f3c9a10-…, amount: 999
The server did not compare the body with the first request and created a second transfer for another amount.
Better
Request POST /v1/transfers, Idempotency-Key: 7f3c9a10-…, amount: 999
First request with the same key, amount: 150
Response 422 Unprocessable Content, nothing created
The key was reused with a different body: that is a client error, and the payment is not made.
Figure 3. Reusing a key with another body: the response code comes from the contract (422 or 409), but a new payment is never acceptable.
What to test. Below is a scenario with four checks: the first request gives 201, a repeat with the same key and body returns the same id, the same key with a different body is rejected, one transfer in the list.
test('same Idempotency-Key does not create a second transfer', async ({ request }) => {
const key = crypto.randomUUID();
const send = (amount: number) =>
request.post('/v1/transfers', {
headers: { 'Idempotency-Key': key },
data: { toAccount: 'UA21...', amount, currency: 'UAH' },
});
const first = awaitsend(150);
const retry = awaitsend(150);
expect(first.status()).toBe(201);
const id = (await first.json()).id;
expect((await retry.json()).id).toBe(id);
const other = awaitsend(999); // same key, different bodyexpect([409, 422]).toContain(other.status());
const list = await (await request.get('/v1/transfers?limit=50')).json();
expect(list.items.filter((t: { id: string }) => t.id === id)).toHaveLength(1);
});
The same key with a different body means the client reused a key by mistake, and silently executing a new payment would be dangerous. The draft advises rejecting such a request with 422, and a request that is still being processed with 409. So the test accepts 409 or 422 and is compared with the contract of a particular service.
The most interesting case: two parallel requests with one key. This is where implementations break, because the check "the key already exists" and writing the key are not atomic:
test('two parallel requests with one key create one transfer', async ({ request }) => {
const key = crypto.randomUUID();
const send = () =>
request.post('/v1/transfers', {
headers: { 'Idempotency-Key': key },
data: { toAccount: 'UA21...', amount: 150, currency: 'UAH' },
});
const [a, b] = awaitPromise.all([send(), send()]);
const ids = newSet<string>();
for (const r of [a, b]) {
expect([200, 201, 409]).toContain(r.status()); // 409 = still in progressif (r.ok()) ids.add((await r.json()).id);
}
expect(ids.size).toBe(1);
});
Limits and common mistakes
A key lives a limited time. Usually 24 hours or more; after that the same key may be accepted as new. A test for the expiry needs a controlled clock or a server with a short TTL.
A key is bound to a user. Someone else's key must not return someone else's response. That is a security check.
A key does not replace business uniqueness. Two different keys with the same intent give two payments, and separate rules protect from that (for example a unique order number).
Storing only success. If a retry after a 500 has a chance to succeed while a 4xx is stored forever, that rule must be in the documentation.
Forgetting that PATCH is not guaranteed to be idempotent. It may need a key or a conditional request with If-Match too.
Check yourself
A PUT without the city field returned 200, and GET shows the old city. What does that mean?
Answer
If the contract says PUT is a full replace, it is a defect: the API behaves like PATCH. If the contract describes a partial update, the defect is in the documentation. Either way the state is checked through GET, not by the response.
What must the server do when the same Idempotency-Key arrives with a different body?
Answer
Not perform a new action and reject the request with an error, 422 by the draft (or 409 by the service contract). Silently executing a new payment under an old key is dangerous, so it is a separate negative test.
Why is it not enough to check that the second request returned 201?
Answer
Because a 201 with a different id means a second payment. The ids in the responses must be compared and the records counted through GET or the history: one transaction must remain in the system.
Related lessons: “HTTP methods, idempotency, PUT vs PATCH”, “Timeouts, retries and idempotency keys”, “Money and repeated requests: races, idempotency, precision, partial failures”.
In an interview.Junior: PUT replaces a resource fully, PATCH changes only the passed fields. A second click on "Pay" can create two payments because POST is not idempotent, so payments use Idempotency-Key. Middle/Senior: For PUT I check through GET that a missing field is reset per the contract. For the key I check a repeat with the same body (the same id, one record), a different body (409 or 422), parallel requests with one key and the binding of the key to a user. I also clarify the key's lifetime and whether an error response is stored.
Testing checklist by method: what to check for GET, POST, PUT, PATCH, DELETE
For each HTTP method check the response (code, headers, body) and the server state afterwards, read with a separate GET. POST: 201, Location, the resource visible via GET, validation, a repeat. PUT: full replacement. PATCH: only the sent field changes. DELETE: a follow-up GET returns 404 and neighbours stay intact. An unsupported method gives 405 with Allow, and GET changes nothing.
API · Methods
What to check for POST /orders so the interview answer is more than "status 201"?
In an interview they ask: "what will you check for POST /orders?". A weak answer: "status 201". A strong one starts from the method: what it guarantees, what must change on the server, what must not. This article gives such a grid for five methods and shows how it turns into automated tests.
How it works
A method defines two kinds of expectations. The first is the response: code, headers, body. The second is the server state: what changed or did not change after the request. Both must be checked, because a response without a state change means "200, but nothing is saved", and a state change without a proper response means the client never learns the result. The state is checked with a separate request, usually GET.
Method
What to check
GET
Does not change state (a repeat gives the same). 200 for an existing id, 404 for a missing one. Filters and pagination. An empty collection gives 200 and []. Someone else's resource is unavailable.
POST
201 and Location (or a body with an id). The created resource is visible through GET. Validation of required fields and types. A duplicate of a unique field. A repeated POST creates a second resource unless there is an idempotency key.
PUT
Full replace: a field that was not sent is reset. A repeat gives the same state. A missing resource is either created (201) or gives 404 by the contract.
PATCH
Only the sent field changes, the rest stays. null versus an absent field. An empty body {}. A read-only field (id, createdAt) is not changed.
DELETE
Success is usually 204. The next GET gives 404. A repeat gives 404 or 204 by the contract. Related data is handled by the rule. Someone else's resource is not deleted.
The table is complemented by a "base grid" of cases common to every endpoint: the happy path; missing authentication (401); someone else's resource (403 or 404 by policy); an invalid body (400 or 422); an unknown id (404); a repeat of the same request.
Example: from the grid to tests
It is convenient to keep the grid as a table instead of copying a test. A new case costs one row:
For DELETE the consequences matter more than the code. The test checks three things: the resource is gone, a repeat does not break, neighbours are not harmed:
test('DELETE: gone, repeatable, no collateral damage', async ({ request }) => {
const { id } = await (await request.post('/v1/orders', { data: { sku: 'A1', qty: 1 } })).json();
const neighbour = await (await request.post('/v1/orders', { data: { sku: 'B2', qty: 1 } })).json();
expect((await request.delete('/v1/orders/' + id)).status()).toBe(204);
expect((await request.get('/v1/orders/' + id)).status()).toBe(404);
// the repeat may be 204 or 404 by contract, but never 500 and never a second effectexpect([204, 404]).toContain((await request.delete('/v1/orders/' + id)).status());
// a neighbour created by the test is untouchedexpect((await request.get('/v1/orders/' + neighbour.id)).status()).toBe(200);
});
The repeat allows 204 or 404 because contracts differ, but never 500 and never a second side effect. "The neighbouring resource is intact" catches a dangerous bug where a DELETE without an id filter removes too much.
404 or 405 on DELETE of a collection
Typical
404 Not Found
Misleading: the /orders collection exists, the method is simply not allowed for it.
Better
405 Method Not Allowed
Describes the problem exactly. The Allow header lists the permitted methods, for example GET, POST.
Figure 1. An unsupported method is neither "not found" nor a server error. The Allow header in a 405 is mandatory per RFC 9110.
Limits and particulars
Method safety. Only POST, PUT, PATCH, DELETE change state. A GET that changes something (GET /orders/17/cancel) is a defect: a prefetch, a crawler or a cache will call it. The check is simple: GET twice and compare the state.
PUT to a missing resource. The API may create it (201) or answer 404. Both are legitimate, but must be documented and the same across endpoints.
Someone else's resource. Answering 403 or 404 is a policy decision: 404 does not reveal that the resource exists. A test compares with the contract.
Races. Two simultaneous PATCHes on one resource and a check that there is no lost update (If-Match, a version).
Common mistakes
Checking only the code. A POST test with 201 but no GET after creation misses "created, but not saved".
Not checking a repeat. Duplicates and lost updates show up exactly on a repeated request.
Skipping 405. A server that answers 500 to an unknown method has a bug that one test line catches.
Taking expectations from your head. The code and behaviour of each method are checked against the service contract.
Check yourself
For PATCH /users/7 with the body {} the server returned 200. What to check?
Answer
Whether the state changed (GET before and after): an empty change changes nothing. The contract alternative is 400 or 422 as "nothing to change". The main thing: no 500 and no fields reset.
Why is it not enough to check 201 after POST?
Answer
Because 201 is only the server's claim that the resource was created, not proof. Read Location or the id, do a GET and make sure the resource exists with the fields that were sent, not merely with the right status.
Which status to expect when calling DELETE /orders without an id?
Answer
405 Method Not Allowed with an Allow header if deleting the whole collection is not supported. 404 is imprecise and 500 is a defect.
Related lessons: “The methods table”, “PUT vs PATCH and Idempotency-Key in fintech”, “What to check when testing an endpoint”.
In an interview.Junior: For POST /orders I check 201 and Location, that the order is visible through GET, validation of required fields, a duplicate and access without a token. Middle/Senior: I start from the method: what must change in the state and what must not. For POST I add a repeated request and an idempotency key, for PUT a full replace, for PATCH the difference between null and an absent field, for DELETE a repeat, the effect on related data and that neighbours are intact. An unsupported method must give 405 with Allow, and a GET must not change data.