10.2 — HTTP Verbs, Idempotency and Safety¶
← Roadmap · Section: 10. Web API Design and REST Prev: 10.1 REST principles · Next: 10.3 Status codes
Markers: 🔥 ⚠️ · Confidence: 🔴 · Last reviewed: —
TL;DR¶
Safe means the request changes nothing. Idempotent means doing it twice has the same effect as doing it once.
GET,HEAD,OPTIONS— safe and idempotent.PUT,DELETE— idempotent, not safe.POST,PATCH— neither. Retrying them can duplicate work.- These are promises you make, not behaviour ASP.NET Core enforces. A
GETthat deletes a record still compiles.
Definitions¶
| Term | What it is | What it means |
|---|---|---|
| Safe | a property of a verb | The request does not change server state. Read-only. |
| Idempotent | a property of a verb | Sending it N times leaves the same state as sending it once. |
GET |
an HTTP verb | Read a resource. Safe, idempotent, cacheable. |
POST |
an HTTP verb | Create, or perform an operation. Neither safe nor idempotent. |
PUT |
an HTTP verb | Replace a resource entirely. Idempotent. |
PATCH |
an HTTP verb | Change part of a resource. Not guaranteed idempotent. |
DELETE |
an HTTP verb | Remove a resource. Idempotent. |
HEAD |
an HTTP verb | Like GET, headers only, no body. |
OPTIONS |
an HTTP verb | Ask what a resource supports. Used by CORS preflight. |
| JSON Patch | a format (RFC 6902) | A list of operations: replace, add, remove. |
| JSON Merge Patch | a format (RFC 7386) | A partial object; present fields are applied. |
| Idempotency key | a technique | A client-supplied ID that makes a POST safe to retry. |
The concept¶
Why these two words matter¶
Networks fail halfway. A client sends a request, the connection drops, and the client has no way to know whether the server processed it. Its only options are to retry or give up.
Safety and idempotency are what tell the client — and every proxy, retry policy and load balancer in between — which of those is safe.
- Safe → retrying costs nothing, because nothing changed.
- Idempotent → retrying is fine, because the second one lands on the same end state.
- Neither → retrying might charge the card twice.
This is not academic. It is exactly why a browser warns you before re-submitting a form, and
why POST needs an idempotency key to be retry-safe (10.13).
The analogy¶
- Safe — reading a thermometer. Read it a hundred times, the room is unchanged.
- Idempotent — setting a thermostat to 20°. Do it once or ten times, it is 20°.
- Neither — turning the temperature up by one. Ten times is very different from once.
That last one is POST, and it is why "just retry it" is not a general answer.
How it works¶
The table to memorise¶
| Verb | Safe | Idempotent | Cacheable | Body? | Typical success |
|---|---|---|---|---|---|
GET |
✅ | ✅ | ✅ | ❌ | 200 |
HEAD |
✅ | ✅ | ✅ | ❌ | 200 |
OPTIONS |
✅ | ✅ | ❌ | ❌ | 200 / 204 |
POST |
❌ | ❌ | ⚠️ rarely | ✅ | 201 / 200 / 202 |
PUT |
❌ | ✅ | ❌ | ✅ | 200 / 204 |
PATCH |
❌ | ⚠️ not guaranteed | ❌ | ✅ | 200 / 204 |
DELETE |
❌ | ✅ | ❌ | ⚠️ usually not | 204 |
Every safe verb is idempotent — if it changes nothing, repeating it obviously changes nothing.
The reverse is not true: DELETE is idempotent but definitely not safe.
Why DELETE is idempotent even though the second call 404s¶
This trips people up. DELETE /orders/42 succeeds; call it again and you get 404.
Different status code, same end state. Idempotency is about the state of the server, not the response you get back. After one call the order is gone; after five it is still gone. That is the guarantee.
⚠️ A common design question follows: should the second DELETE return 404 or 204? Both are
defensible. 204 every time is friendlier to retry logic — the client asked for it to be gone
and it is gone. 404 is more informative. Pick one, document it, be consistent.
PUT vs PATCH — the one that gets asked¶
// Existing: { "name": "Ada", "email": "ada@x.com", "phone": "555-1234" }
// PUT /users/1 with { "name": "Ada Lovelace", "email": "ada@x.com" }
// → REPLACES the whole resource. phone is now NULL — it wasn't in the payload.
// PATCH /users/1 with { "name": "Ada Lovelace" }
// → Changes just the name. email and phone survive.
⚠️ PUT is a full replacement, and omitted fields are wiped. This is the single most common
bug in a hand-rolled PUT: the developer treats it as "update", the client sends only the changed
fields, and everything else is silently nulled.
Why PATCH is not guaranteed idempotent is the follow-up question. Because a patch can express
a relative change:
[ { "op": "replace", "path": "/name", "value": "Ada" } ] ← idempotent
[ { "op": "add", "path": "/tags/-", "value": "vip" } ] ← ⚠️ NOT — appends every time
The second one appends to an array. Send it three times, you get three vip tags. The verb can
be used idempotently; the spec does not promise it.
The two PATCH formats¶
| JSON Patch (RFC 6902) | JSON Merge Patch (RFC 7386) | |
|---|---|---|
| Content type | application/json-patch+json |
application/merge-patch+json |
| Shape | A list of operations | A partial object |
| Can express "remove" | ✅ Explicit remove op |
⚠️ Only via null |
| Can distinguish "set to null" from "leave alone" | ✅ | ❌ No |
| Arrays | ✅ Index-level ops | ❌ Whole-array replace |
| ASP.NET Core support | JsonPatchDocument<T> |
Manual, or nullable wrappers |
⚠️ The null-versus-absent problem is real. With merge patch, {"phone": null} and a payload
that omits phone deserialize to the same thing in C# — both give you null. You cannot tell
"clear the phone number" from "don't touch the phone number" without extra machinery.
⚠️ And JsonPatchDocument<T> still needs Microsoft.AspNetCore.Mvc.NewtonsoftJson — it is
built on Newtonsoft, not System.Text.Json. Adding it changes serialization behaviour for the
whole app unless you configure it carefully (10.5).
The deeper detail — these are promises, not enforcement¶
⚠️ Nothing in ASP.NET Core stops you writing a [HttpGet] action that deletes a row. It will
compile and run.
But things around you assume the contract holds:
- Browsers and proxies prefetch and cache
GET. AGETwith side effects gets triggered by a link preview, a crawler, or a "prefetch on hover" feature. - Retry policies retry idempotent verbs automatically. Polly, HTTP clients and load balancers do this (19.11).
- CORS treats
GETas a simple request — no preflight, so it reaches your server before any CORS check (10.10).
The classic disaster: an admin panel with GET /users/5/delete links. A crawler indexes the
page and deletes every user. That is not hypothetical — it has happened repeatedly, most famously
to a Google Accelerator user in 2005.
Making POST retry-safe¶
Since POST is not idempotent, the fix is an idempotency key — the client generates a unique
ID and sends it with the request:
The server stores the key with the result. A retry with the same key returns the original result instead of charging again. This is how Stripe and every serious payments API work, and it is the expected answer to "how do you make a payment endpoint safe to retry?" (10.13).
Code¶
[ApiController]
[Route("api/users")]
public sealed class UsersController : ControllerBase
{
private readonly IUserService _users;
public UsersController(IUserService users) => _users = users;
// SAFE + IDEMPOTENT. No side effects — not even a "last viewed" write.
[HttpGet("{id:int}")]
public async Task<ActionResult<UserDto>> Get(int id, CancellationToken ct)
{
var user = await _users.FindAsync(id, ct);
return user is null ? NotFound() : Ok(user);
}
// NOT idempotent. Two identical calls create two users — unless an idempotency key is used.
[HttpPost]
public async Task<ActionResult<UserDto>> Create(CreateUserRequest req, CancellationToken ct)
{
var created = await _users.CreateAsync(req, ct);
return CreatedAtAction(nameof(Get), new { id = created.Id }, created);
}
// IDEMPOTENT — full replacement.
// ⚠️ Anything absent from the request is CLEARED. That is what PUT means.
[HttpPut("{id:int}")]
public async Task<IActionResult> Replace(int id, ReplaceUserRequest req, CancellationToken ct)
{
// req is a complete representation — every field required, no optionals
var found = await _users.ReplaceAsync(id, req, ct);
return found ? NoContent() : NotFound();
}
// PATCH with JSON Patch. Requires Microsoft.AspNetCore.Mvc.NewtonsoftJson.
[HttpPatch("{id:int}")]
[Consumes("application/json-patch+json")]
public async Task<IActionResult> Patch(
int id, [FromBody] JsonPatchDocument<UpdateUserDto> patch, CancellationToken ct)
{
var user = await _users.FindForUpdateAsync(id, ct);
if (user is null) return NotFound();
var dto = user.ToUpdateDto();
// ⚠️ Apply to a DTO, never straight to the entity — a patch document can otherwise
// target ANY property, including IsAdmin. This is over-posting with extra steps.
patch.ApplyTo(dto, ModelState);
// ⚠️ ApplyTo records failures in ModelState instead of throwing.
// Skip this check and an invalid patch silently does nothing.
if (!ModelState.IsValid) return ValidationProblem(ModelState);
if (!TryValidateModel(dto)) return ValidationProblem(ModelState);
await _users.ApplyAsync(id, dto, ct);
return NoContent();
}
// IDEMPOTENT. Returns 204 whether or not it existed — friendlier to retries.
[HttpDelete("{id:int}")]
public async Task<IActionResult> Delete(int id, CancellationToken ct)
{
await _users.DeleteAsync(id, ct); // no-op if already gone
return NoContent();
}
}
The Patch action carries three separate traps worth reading slowly:
ApplyTo targets a DTO, not the entity. A JsonPatchDocument<User> lets the client write any
property on User — including IsAdmin and PasswordHash. Patching a purpose-built DTO limits
the blast radius (11.10).
ApplyTo(dto, ModelState) does not throw. It records the error and carries on. Omit the
ModelState.IsValid check and a malformed patch returns 204 having changed nothing.
TryValidateModel is separate. [ApiController] validates the incoming patch document, not
the object after the patch has been applied — so data annotations on the DTO are not checked unless
you ask (10.4).
Interview questions¶
Q: What is the difference between safe and idempotent?
Safe means the request does not change server state at all — GET, HEAD and OPTIONS.
Idempotent means repeating it leaves the same end state as doing it once, which covers PUT and
DELETE as well as all the safe verbs. Every safe verb is idempotent, but not the reverse: DELETE
changes plenty, it just does not change anything further on the second call. It matters because
when a connection drops mid-request the client cannot tell whether the server processed it, and
these properties are what tell it whether retrying is safe.
Q: Why is DELETE idempotent if the second call returns 404?
Because idempotency is about server state, not the response. After the first call the resource is gone; after the fifth it is still gone. The status code differs but the state does not, and that is the guarantee retry logic depends on. Whether to return 404 or 204 on the repeat is a design choice — 204 is kinder to retries, 404 is more informative — but either way the verb is idempotent.
Q: What is the difference between PUT and PATCH?
PUT replaces the entire resource, so anything absent from the payload gets cleared — that is the
usual bug, where a client sends only the changed fields and everything else is nulled. PATCH
applies a partial change. PUT is idempotent by definition; PATCH is not guaranteed to be,
because a patch operation can be relative — appending to an array three times gives you three
entries. In ASP.NET Core, JSON Patch needs the Newtonsoft package, and you should apply the patch
to a DTO rather than the entity, or the client can target any property on it.
Q: How do you make a POST endpoint safe to retry?
An idempotency key. The client generates a unique ID per logical operation and sends it as a
header; the server stores the key alongside the result, so a retry with the same key returns the
original response rather than performing the work again. That is how Stripe handles payments. The
alternative — reshaping the operation so it can be a PUT to a client-chosen ID — works when the
client can pick the identifier, but for something like charging a card the idempotency key is the
standard answer.
Traps ⚠️¶
GETwith side effects. Crawlers, prefetch and link previews will trigger it.GET /users/5/deletelinks in an admin UI. Crawlers have wiped real databases this way.- Treating
PUTas "update" — omitted fields get nulled. - Assuming
PATCHis idempotent. Relative operations are not. ApplyTofailures are silent unless you checkModelState.JsonPatchDocument<Entity>lets the client patchIsAdmin. Use a DTO.[ApiController]does not validate the post-patch object — callTryValidateModel.- JSON Patch needs the Newtonsoft package, which changes serialization app-wide.
- Merge patch cannot distinguish
nullfrom absent. - Retrying
POSTwithout an idempotency key duplicates orders and charges.
Related¶
- 10.1 REST principles — where the verbs come from
- 10.3 Status codes — what to return from each verb
- 10.13 Idempotency keys and ETags — making
POSTretry-safe - 10.4
[ApiController]— what it validates and what it does not - 10.5 Content negotiation and JSON — the Newtonsoft question
- 11.10 Over-posting — why patch a DTO
- 19.11 Polly resilience — retries in practice
- 10.10 CORS — why
GETskips preflight