Skip to main content
01

HTTP methods, status codes and idempotency

EasyHTTPRESTIdempotency

What do the main HTTP methods mean, which status codes should an API return, and what does idempotent mean?

TL;DR

An operation is idempotent if doing it once or many times leaves the server in the same state. GET, PUT and DELETE are idempotent; POST and usually PATCH aren't. Safe methods (GET, HEAD, OPTIONS) don't change state at all. This matters because networks fail and clients retry: retrying an idempotent request is harmless, but retrying a POST /payments can charge twice unless you add an idempotency key.

Key points

MethodUseSafeIdempotent
GETRead✅✅
POSTCreate, or run an action❌❌
PUTReplace the whole resource❌✅
PATCHPartial update❌Not guaranteed
DELETERemove❌✅

Status codes worth knowing:

  • 200 OK, 201 Created (with a Location header), 204 No Content.
  • 400 invalid input, 401 not authenticated, 403 authenticated but not allowed, 404 not found, 409 conflict, 422 validation failed, 429 rate limited.
  • 500 server bug, 502/503/504 upstream or availability problems.

Idempotency keys: the client sends a unique Idempotency-Key header. The server stores the key with the result, and a retry with the same key returns the stored result instead of acting again.

Example

http
POST /payments
Idempotency-Key: 7f3c2a90-...
Content-Type: application/json

{ "amount": 100, "currency": "ILS" }

Common follow-ups

  • Is DELETE still idempotent if the second call returns 404? Yes. Idempotency is about server state, not the response code.
  • Where do you store idempotency keys? In the database (a unique constraint on the key), with a TTL, written in the same transaction as the side effect.

What interviewers look for

Tip

Define idempotency by server state, connect it to retries, and know the idempotency-key pattern for POST.

  • Red flag: returning 200 with { "error": ... } in the body, or mixing up 401 and 403.

Was this helpful?

Related questions