Requests, responses and methods
Here is a complete HTTP/1.1 request, exactly as it travels over the connection:
POST /api/orders HTTP/1.1
Host: shop.example
Content-Type: application/json
Content-Length: 34
Authorization: Bearer eyJhbGciOi...
{"productId": 7, "quantity": 2}And the response:
HTTP/1.1 201 Created
Content-Type: application/json
Location: /api/orders/1001
Content-Length: 41
{"id": 1001, "status": "PENDING_PAYMENT"}Both have the same shape: a first line, headers (one Name: value per line), an empty line, then the optional body. The request’s first line has the method, the path and the version; the response’s first line has the version and the status code.
The method says what the client wants to do with the thing at that path:
| Method | Meaning | Body? | Example |
|---|---|---|---|
GET | Read it | No | GET /api/orders/1001 |
POST | Create something new, or start an action | Yes | POST /api/orders |
PUT | Replace it completely with this | Yes | PUT /api/users/42/address |
PATCH | Change part of it | Yes | PATCH /api/orders/1001 with {"status": "CANCELLED"} |
DELETE | Remove it | Usually no | DELETE /api/cart/items/7 |
Two properties matter more than the names:
- Safe methods (
GET,HEAD,OPTIONS) must not change anything. Browsers prefetch links, search engines crawl them, link previews in chat apps open them, all assuming that aGETis harmless. - IdempotentIdempotencyAn operation is idempotent if doing it twice has the same effect as doing it once.Open in glossary → methods give the same result whether you send them once or five times:
GET,PUT,DELETE(deleting an already deleted item leaves it deleted).POSTis not: sending “create an order” twice creates two orders. That’s why an app can safely retry aPUTafter a timeout, but must be careful withPOST.
- Semantics (RFC 9110): safe = no intended state change (logging and metrics are fine); idempotent = the intended effect of N identical requests equals one.
PUTandDELETEare idempotent,PATCHis not by definition (a JSON Patchaddto an array repeats), though many PATCH bodies happen to be. - Retries: clients and proxies may automatically retry idempotent requests after a connection failure (OkHttp, browsers, Envoy with retry policies); never non-idempotent ones. Make
POSTretryable with an Idempotency-Key header: the server stores the key with the result and returns the same result for a repeated key. See the idempotent payment API question. HEADreturns headers only (size,ETag, existence checks);OPTIONSis used by CORS preflights.- GET with a body has no defined meaning; many proxies, CDNs and clients drop it. For complex search queries use
POST /search(or the newQUERYmethod draft, not yet widely supported). - URL length: no limit in the spec, but around 8 KB is a safe maximum through proxies and servers (many return 414 above it); long filter lists belong in a body.
- Methods and caching: only
GETandHEADresponses are cached by default;POSTresponses rarely.
Predict the output
The request below is sent to a real web server over a plain TCP connection. It has a method, a path and a version, but no headers at all. What comes back?
printf 'GET / HTTP/1.1\r\nConnection: close\r\n\r\n' | nc example.com 80 | head -1HTTP/1.1 requires a Host header. One IP address usually serves many sites (virtual hosting, CDNs), and Host tells the server which one you mean, so a request without it is rejected with 400. Add Host: example.com and the same request works. (The empty line, two CRLFs, is what ends the headers; without it the server would indeed keep waiting.)
# -v shows the request (>) and response (<) headers
curl -v https://httpbin.org/get
# send JSON with the right headers
curl -X POST https://httpbin.org/post \
-H 'Content-Type: application/json' \
-d '{"productId": 7, "quantity": 2}'
# only the response headers (sends HEAD)
curl -I https://example.com/
# a retry-safe POST: the server deduplicates by key
curl -X POST https://api.shop.example/orders \
-H 'Idempotency-Key: 6f1c2f5e-8a0b-4c55-9d1e-2b7a5c1d9e44' \
-H 'Content-Type: application/json' -d @order.jsonThe cart that emptied itself
Tap the line with the bug.
@RestController
@RequestMapping("/api/cart")
class CartController(private val carts: CartService) {
@GetMapping("/{cartId}/clear")
fun clear(@PathVariable cartId: Long): ResponseEntity<Unit> {
carts.removeAllItems(cartId)
return ResponseEntity.noContent().build()
}
}@RestController
@RequestMapping("/api/cart")
class CartController {
private final CartService carts;
CartController(CartService carts) { this.carts = carts; }
@GetMapping("/{cartId}/clear")
ResponseEntity<Void> clear(@PathVariable long cartId) {
carts.removeAllItems(cartId);
return ResponseEntity.noContent().build();
}
}const router = express.Router();
router.get('/api/cart/:cartId/clear', async (req, res) => {
await carts.removeAllItems(Number(req.params.cartId));
res.status(204).end();
});Hint: Which programs, other than your user clicking, might send a GET to that URL?
A GET is supposed to be safe, and lots of software relies on that. When the link is in an email, the mail provider’s link scanner opens it to check for malware. When it’s pasted into a chat, the app fetches it to build a preview. Browsers may prefetch it. Each of them empties the customer’s cart without anyone clicking.
Actions that change data use a method that says so, here DELETE (or POST for actions that aren’t removals). A link in an email should lead to a page with a button that sends that request:
@DeleteMapping("/{cartId}/items")
fun clear(@PathVariable cartId: Long): ResponseEntity<Unit> {
carts.removeAllItems(cartId)
return ResponseEntity.noContent().build()
}@DeleteMapping("/{cartId}/items")
ResponseEntity<Void> clear(@PathVariable long cartId) {
carts.removeAllItems(cartId);
return ResponseEntity.noContent().build();
}router.delete('/api/cart/:cartId/items', async (req, res) => {
await carts.removeAllItems(Number(req.params.cartId));
res.status(204).end();
});The same rule protects you from a security bug: a state-changing GET can be triggered from any other website with a simple image tag, which is the easiest form of cross-site request forgery.
Deep diveMaking POST safe to retryInterview favorite
“The app creates an order, the response times out, and the user taps again. How do you avoid two orders?” The network can fail after the server committed, so the client can’t know whether the first request worked. Retrying is necessary; making it harmless is the design.
- The client generates a unique Idempotency-Key (a UUID) when the user starts the action, not per attempt, and sends it with every retry.
- The server, in the same transaction as creating the order, inserts the key into a table with a unique constraint, along with the request fingerprint and, when done, the response.
- A repeated key with the same fingerprint returns the stored response (same status and body). A repeated key with a different body is a client bug: 422. A request still in progress for that key gets 409, and the client retries later.
- Keys expire after a sensible window (Stripe keeps them 24 hours).
Alternatives: a client-generated resource id with PUT /orders/{uuid} (idempotent by nature), or natural unique constraints (one payment per order id). Name the race: two retries arriving at once must not both pass the “key not seen” check, which is why the unique constraint, not a prior SELECT, is the guard. See Transactions.
- Request: method, target, version, headers, blank line, body. Response: status line, headers, body.
- Safe: GET, HEAD, OPTIONS. Idempotent: plus PUT, DELETE. POST and PATCH aren’t; automatic retries apply only to idempotent requests.
- Idempotency-Key for POST: stored with the result under a unique constraint; same key returns the same response.
- No bodies on GET (dropped by intermediaries); keep URLs under about 8 KB; state-changing GETs get triggered by scanners, previews and CSRF.
POST /api/orders HTTP/1.1
Host: shop.example
Content-Type: application/json
Idempotency-Key: 6f1c2f5e-8a0b-4c55-9d1e-2b7a5c1d9e44
{"productId": 7, "quantity": 2}Check this part
Which method is NOT idempotent?
Why must GET requests not change data?
A client retries a POST after a timeout. How does the server avoid a duplicate?
A search endpoint takes a large JSON filter. Which is the safest choice?