Which HTTP methods are safe and which are idempotent?
Safe methods (GET, HEAD, OPTIONS) don't change server state. Idempotent methods (GET, PUT, DELETE and the safe ones) give the same result when repeated. POST is neither, and PATCH is not guaranteed idempotent.
Explain it simply
Two separate ideas:
Safe: the request does not modify anything. Calling it ten times changes nothing. GET, HEAD, OPTIONS.
Idempotent: calling it once or ten times leaves the server in the same final state. The response may differ, but the effect does not.
Think of a lift button: pressing "3" five times is the same as pressing it once (idempotent). Dropping a coin in a donation box five times is five donations (not idempotent).
- GET: safe and idempotent.
- PUT: replaces a resource with the given content; repeating gives the same state.
- DELETE: the first call deletes; later calls find nothing, but the state (resource absent) is the same.
- POST: usually creates something new each time, so repeats create duplicates.
- PATCH: depends; "set name to X" is idempotent, "add 10 to balance" is not.
This matters because networks time out and clients retry. Idempotent calls are safe to retry blindly.
Example
PUT /users/5 {"city":"Pune"} run 3 times -> city = Pune
DELETE /users/5 run 3 times -> user gone
POST /payments {"amount":500} run 3 times -> 3 payments!For POST you need an idempotency key to make retries safe.
What to say in the interview
"Safe means no state change; idempotent means repeating has the same effect as doing it once. GET, PUT and DELETE are idempotent; POST is not. Since clients retry on timeouts, I make non-idempotent operations safe with idempotency keys."