Part 4 of 9 · 2 min read
Methods, safe and idempotent
What GET, POST, PUT and DELETE mean, and the two properties that decide when a retry is allowed.
Think of a lift button. Pressing "up" twice does not take the lift up two floors. Pressing a "buy" button twice in a shop could buy two things. The first button is harmless to repeat. The second is not.
HTTP methods carry this difference. The four common methods map to create, read, update and delete.
| Request | Meaning |
|---|---|
POST /products |
Create a product. The reply gives the address of the new one. |
GET /products |
List products. The query string filters, sorts and pages. |
GET /products/42 |
Read product 42. |
PUT /products/42 |
Replace or update product 42. |
DELETE /products/42 |
Delete product 42. |
Two properties tell how safe it is to repeat each one.
Safe method
A safe method changes nothing visible on the server. It can be cached and repeated freely.
Example: GET /products/42 can be sent a hundred times, and the product stays the same.
Idempotent
An operation is idempotent if doing it many times leaves the same end state as doing it once.
Example: "set the price of product 42 to 999" is idempotent. "Add 10 to the price" is not, because each repeat adds again.
The book gives this table.
| Method | Safe | Idempotent |
|---|---|---|
| GET | Yes | Yes |
| PUT | No | Yes |
| DELETE | No | Yes |
| POST | No | No |
Why does idempotency matter? Networks lose replies. A client sends a request, the server does the work, and the reply is lost. The client cannot tell whether the work happened. If the call is idempotent, the client can simply send it again. If it is not, a blind retry may do the work twice.
A worked example. A shop has 50 units of an item.
PUT /items/9with the body{"stock": 48}. The server stores 48. The reply is lost. The client retries. The server stores 48 again. The end state is 48.POST /items/9/sellwith the body{"count": 2}. The server takes 2 away, so stock is 48. The reply is lost. The client retries. The server takes 2 away again, so stock is 46. Two units were sold that no one asked for.
The first call is safe to retry. The second is not.
For the curious For the curious
DELETE is idempotent, but its reply can differ. The first call may return 200, and a repeat may return 404 because the item is already gone. The end state is the same, which is what idempotent means.
Check yourself:
- Is
DELETE /products/42safe? Is it idempotent? - Why is "add 10 to the price" a poor operation to send over an unreliable network?