Skip to content
Commitwise
Menu
Networking

HTTP: methods, status codes and headers

What an HTTP request and response really look like. Covers methods and which ones are safe and idempotent, the GET that deleted data, status codes from 200 to 504 (401 vs 403, 302 vs 307, 502 vs 503 vs 504), headers like Host, Content-Type and Content-Length, the JSON body sent as text/plain, compression, and request smuggling.

beginner

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

HTTP is the language apps and servers speak. Every API call, image download and web page is an HTTP request answered by an HTTP response, and both are surprisingly simple: a line of text, some headers, an optional body. Knowing that format well is what lets you read a curl -v output, choose the right status code, and spot why a request “works in Postman but not in the app”.

This lesson is about the protocol itself; designing whole APIs on top of it is in Building a REST API and API design: REST, GraphQL and gRPC. Underneath, HTTP runs over the connections from TCP vs UDP.

New to some of these? Open what you need, or skip ahead.

Basics:Client, server and URL

A client (an app, a browser) sends requests; a server answers them. A URL like https://shop.example/api/orders?page=2 names what you want: the scheme (https), the host (shop.example), the path (/api/orders) and the query (page=2).

Basics:JSON

JSON is the text format most APIs use for data: objects in braces with "name": value pairs, lists in square brackets, strings in double quotes. An order might be sent as the text of an object with an id, a status and a list of items.

Part Not started

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:

MethodMeaningBody?Example
GETRead itNoGET /api/orders/1001
POSTCreate something new, or start an actionYesPOST /api/orders
PUTReplace it completely with thisYesPUT /api/users/42/address
PATCHChange part of itYesPATCH /api/orders/1001 with {"status": "CANCELLED"}
DELETERemove itUsually noDELETE /api/cart/items/7

Two properties matter more than the names:

  • Semantics (RFC 9110): safe = no intended state change (logging and metrics are fine); idempotent = the intended effect of N identical requests equals one. PUT and DELETE are idempotent, PATCH is not by definition (a JSON Patch add to 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 POST retryable 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.
  • HEAD returns headers only (size, ETag, existence checks); OPTIONS is 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 new QUERY method 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 GET and HEAD responses are cached by default; POST responses 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 -1
# -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.json

The cart that emptied itself

Spot the bugA 'clear cart' link in an email

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();
});

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.

  1. The client generates a unique Idempotency-Key (a UUID) when the user starts the action, not per attempt, and sends it with every retry.
  2. 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.
  3. 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.
  4. 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

  1. Which method is NOT idempotent?

  2. Why must GET requests not change data?

  3. A client retries a POST after a timeout. How does the server avoid a duplicate?

  4. A search endpoint takes a large JSON filter. Which is the safest choice?

A request is a method and path, headers and an optional body; a response is a status line, headers and a body. Methods say what to do: GET reads, POST creates or triggers, PUT replaces, PATCH changes part, DELETE removes. Safe methods change nothing; idempotent ones can be repeated with the same effect, which decides what can be retried.

Part Not started

Status codes

The status codeHTTP status codeThe three-digit number in every HTTP response that says how the request went.Open in glossary → is a three-digit number that tells the client what happened. The first digit is the class:

ClassMeansWho should act
2xxIt workedNobody
3xxLook somewhere elseThe client follows the redirect
4xxThe request is wrongThe client must change something
5xxThe server failedThe server team; the client may retry later

The ones you’ll use and see most:

CodeNameWhen
200OKSuccess with a body
201CreatedPOST created something; Location says where
204No ContentSuccess, nothing to return (a delete)
301 / 308Moved PermanentlyThe URL changed for good
302 / 307Found / Temporary RedirectGo there for now
304Not ModifiedYour cached copy is still good
400Bad RequestMalformed request (invalid JSON, missing field)
401UnauthorizedYou’re not logged in (no or invalid token)
403ForbiddenYou’re logged in, but not allowed
404Not FoundNothing at this path
409ConflictClashes with the current state (email already taken, outdated version)
422Unprocessable ContentValid JSON, invalid values (quantity is −3)
429Too Many RequestsRate limited; Retry-After says when to try again
500Internal Server ErrorThe server crashed or hit a bug
502Bad GatewayA proxy got a bad or no response from the server behind it
503Service UnavailableOverloaded or down for maintenance
504Gateway TimeoutA proxy waited too long for the server behind it

The pair that confuses everyone: 401 means “who are you?” (log in again), 403 means “I know who you are, and the answer is no”. The names are historical; the meanings are what matter.

  • Redirect methods: on 301 and 302, browsers and fetch change a POST to a GET (historical behaviour, now allowed by the spec); 303 means “now GET this” on purpose (post/redirect/get). 307 and 308 keep the method and body. Use 308 for permanent API moves, 307 for temporary ones.
  • Client errors: 400 for unparseable input, 422 for semantic validation (pick one convention and keep it), 409 for state conflicts (optimistic locking, duplicates), 412 for failed If-Match preconditions, 413 for oversized bodies, 415 for a wrong Content-Type. 404 vs 403 for resources the caller may not see: returning 404 avoids revealing they exist.
  • 401 must carry WWW-Authenticate; mobile clients treat 401 as “refresh the token or log out”, so returning 401 for permission problems logs users out.
  • Retryable: 408, 429, 502, 503, 504 (with backoff and jitter, honouring Retry-After); 500 only for idempotent requests and only a little. Never retry other 4xx.
  • Error bodies: a consistent format such as RFC 9457 problem details (application/problem+json with type, title, status, detail), plus a request id for support.
  • 200 with an error body ({"success": false}) breaks caching, monitoring and client error handling; GraphQL is the notable exception by design.

Predict the output

An app sends a POST with a body to each URL. /old-a answers 302 Found and /old-b answers 307 Temporary Redirect, both to /target. With fetch's default redirect handling, what reaches /target?

await fetch('https://api.shop.example/old-a', { method: 'POST', body: 'x=1' });
await fetch('https://api.shop.example/old-b', { method: 'POST', body: 'x=1' });
@PostMapping("/api/orders")
fun create(@RequestBody @Valid request: CreateOrder): ResponseEntity<OrderDto> {   // @Valid failure -> 400
    val order = orders.create(request)
    return ResponseEntity.created(URI.create("/api/orders/${order.id}")).body(order)  // 201 + Location
}

@GetMapping("/api/orders/{id}")
fun get(@PathVariable id: Long, user: CurrentUser): ResponseEntity<OrderDto> {
    val order = orders.find(id) ?: return ResponseEntity.notFound().build()          // 404
    if (order.customerId != user.id) return ResponseEntity.notFound().build()        // hide others' orders
    return ResponseEntity.ok(order)                                                   // 200
}
@PostMapping("/api/orders")
ResponseEntity<OrderDto> create(@RequestBody @Valid CreateOrder request) {         // @Valid failure -> 400
    OrderDto order = orders.create(request);
    return ResponseEntity.created(URI.create("/api/orders/" + order.id())).body(order);  // 201 + Location
}

@GetMapping("/api/orders/{id}")
ResponseEntity<OrderDto> get(@PathVariable long id, CurrentUser user) {
    return orders.find(id)
            .filter(o -> o.customerId() == user.id())                              // hide others' orders
            .map(ResponseEntity::ok)                                               // 200
            .orElse(ResponseEntity.notFound().build());                            // 404
}
router.post('/api/orders', async (req, res) => {
  const parsed = CreateOrder.safeParse(req.body);
  if (!parsed.success) return res.status(400).json({ title: 'Invalid order', errors: parsed.error.issues });
  const order = await orders.create(parsed.data);
  res.status(201).location(`/api/orders/${order.id}`).json(order);                // 201 + Location
});

router.get('/api/orders/:id', async (req, res) => {
  const order = await orders.find(Number(req.params.id));
  if (!order || order.customerId !== req.user.id) return res.sendStatus(404);     // hide others' orders
  res.json(order);                                                                 // 200
});

Practice: choose the status code

Exerciseeasy

What should the server answer?

  1. A new user registers successfully.
  2. A user registers with an email that already has an account.
  3. A request has no access token.
  4. A logged-in customer opens another customer’s order.
  5. A customer deletes an item from their cart.
  6. The app sends 300 requests in a minute; the limit is 100.
  7. The API server is fine, but the payment provider it calls doesn’t answer in time, and the server reports that.
›

For each one, ask first: did it work (2xx), is the client’s request the problem (4xx), or did the server side fail (5xx)?

SolutionTry it yourself first
  1. 201 Created, with a Location header pointing to the new user.
  2. 409 Conflict: the request is fine, but it clashes with existing data. (Some APIs use 422; for registration, consider the privacy angle of telling anyone which emails are registered.)
  3. 401 Unauthorized: the client must log in.
  4. 404 Not Found (or 403 Forbidden). 404 doesn’t even reveal that the order exists, which is the safer choice for other people’s data.
  5. 204 No Content: done, nothing to return.
  6. 429 Too Many Requests, with Retry-After: 30 (seconds) so the app knows when to try again.
  7. 504 Gateway Timeout if your server acts as a gateway to the provider, or 502 if the provider answered with garbage. Many APIs return 503 with Retry-After for “a dependency is down”. The point is that it’s a 5xx: the client did nothing wrong.
Deep dive502, 503 or 504: which hop failed?Interview favorite

A typical request passes a CDN, a load balancer, maybe an API gateway, and then the app. The 5xx code, and who generated it, tells you where to look.

  • 502 Bad Gateway: a proxy connected to the next hop and got something invalid, or the connection was refused or reset. Typical causes: the app crashed or is restarting, it listens on the wrong port or interface, it closed a keep-alive connection the proxy reused (app keep-alive timeout shorter than the proxy’s), or a response header was too large for the proxy.
  • 503 Service Unavailable: the proxy has no healthy target (all failing health checks, nothing deployed, scaled to zero), or the app itself sheds load. Look at health checks and autoscaling.
  • 504 Gateway Timeout: the proxy connected but the answer didn’t come within its timeout. The app is slow (database, a downstream call) or stuck. Compare the proxy’s timeout with the app’s own timeouts: if the proxy gives up at 30 s and the app’s database query runs 60 s, the app keeps working on a request nobody is waiting for.
  • 500: generated by the app itself, so the app’s logs have the stack trace.

How to tell who answered: the response body and headers (an HTML error page from NGINX or the CDN vs your JSON error format, Server, Via, cf-ray), and the access logs at each hop: the load balancer logs both its own status and the target’s. Good systems pass a request id through every hop so one search finds all of them.

Rules worth stating: timeouts should decrease inward (client > CDN > load balancer > app > database) so the inner layer fails first with a meaningful error, and retries should happen at one layer only, or a single slow call turns into dozens.

  • 301/302 turn POST into GET; 307/308 keep method and body; 303 for post/redirect/get.
  • 401 = not authenticated (with WWW-Authenticate; clients log out), 403 = not allowed; 404 to hide existence. 409 conflicts, 412 precondition, 422 validation, 429 + Retry-After.
  • Retry 408, 429, 502, 503, 504 with backoff; 500 sparingly and only if idempotent.
  • 502 bad or refused upstream, 503 no healthy target or shedding, 504 upstream too slow; timeouts decrease inward, retry at one layer.
  • Errors as RFC 9457 problem details with a request id; no 200-with-error.
HTTP/1.1 429 Too Many Requests
Retry-After: 30
Content-Type: application/problem+json

{"type": "https://shop.example/errors/rate-limit", "title": "Too many requests", "status": 429}

Check this part

  1. A request has an expired access token. Which status code?

  2. Which class of codes means the server failed, not the request?

  3. An endpoint moves permanently and clients POST to it. Which redirect?

  4. The load balancer returns 504 while the app logs show the request finished after 45 s. What happened?

Status codes come in classes: 2xx success, 3xx redirection, 4xx client errors, 5xx server errors. Key ones: 200, 201, 204, 301/302 vs 307/308 (which keep the method), 304, 400, 401 (not authenticated) vs 403 (not allowed), 404, 409, 422, 429 with Retry-After, 500, 502, 503 and 504, which tell you which hop failed.

Part Not started

Headers

Headers are the request’s and response’s metadata: information about the message rather than the message itself. Header names don’t care about upper or lower case (content-type and Content-Type are the same header).

The ones every app developer meets:

HeaderSent bySays
HostClientWhich site on this server (required)
Content-TypeBothWhat the body is: application/json, text/html; charset=utf-8, multipart/form-data…
Content-LengthBothHow many bytes the body has
AcceptClientWhich formats it wants back
Accept-EncodingClientWhich compression it understands: gzip, br
Content-EncodingServerHow the body is compressed
AuthorizationClientCredentials, usually Bearer <token>
User-AgentClientWhich app or browser, and its version
LocationServerWhere a redirect goes, or where a created resource lives
Retry-AfterServerWhen to try again, after 429 or 503

Content-Type is the one that causes the most “it works in Postman” bugs. The server decides how to read the body from it. If the app sends JSON but doesn’t say so, many server frameworks don’t try to parse it and see an empty body, so validation fails with 400 or the fields arrive as null.

Compression happens through headers too. The client says Accept-Encoding: gzip, br, and the server may compress the body and answer with Content-Encoding: gzip. JSON typically shrinks to a fifth of its size or less. Most HTTP libraries add the header and unpack the body automatically, but tools like curl only do it when asked (--compressed).

  • Framing a body: Content-Length, or Transfer-Encoding: chunked in HTTP/1.1 when the size isn’t known up front (streaming); HTTP/2 and HTTP/3 use their own frames, and chunked encoding is forbidden there. Disagreeing framing between hops is the root of request smuggling (below).
  • Content negotiation: Accept, Accept-Language, Accept-Encoding; responses that vary by them need Vary so caches keep separate copies.
  • Compression: Brotli (br) or zstd for text, gzip as fallback; don’t compress already compressed data (images, video) or tiny bodies, and be careful compressing responses that mix secrets with attacker-controlled text over TLS (the BREACH attack).
  • Custom headers: no X- prefix for new ones (RFC 6648), but X-Request-Id, X-Forwarded-For and friends persist; the standard alternative is Forwarded. Strip client-supplied forwarding headers at the edge.
  • Limits: servers cap total header size (often 8 to 16 KB); large cookies or JWTs cause 431 or a bare 400 from a proxy before the app sees anything.
  • HTTP/2 and HTTP/3 require lowercase header names and move the request line into pseudo-headers (:method, :path, :authority).

Predict the output

curl asks for gzip in a header but isn't told to decompress (no --compressed). What do the first bytes of the output look like?

curl -s -H 'Accept-Encoding: gzip' https://www.google.com/ | head -c 16 | xxd
// OkHttp
val json = """{"productId": 7, "quantity": 2}"""
val request = Request.Builder()
    .url("https://api.shop.example/api/orders")
    .header("Authorization", "Bearer $token")
    .header("Idempotency-Key", key)
    .post(json.toRequestBody("application/json".toMediaType()))   // sets Content-Type
    .build()
client.newCall(request).execute().use { response ->
    println("${response.code} ${response.header("Location")}")
}
// java.net.http.HttpClient
HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.shop.example/api/orders"))
        .header("Authorization", "Bearer " + token)
        .header("Idempotency-Key", key)
        .header("Content-Type", "application/json")              // not added automatically
        .POST(HttpRequest.BodyPublishers.ofString("{\"productId\": 7, \"quantity\": 2}"))
        .build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode() + " " + response.headers().firstValue("Location").orElse(""));
const response = await fetch('https://api.shop.example/api/orders', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${token}`,
    'Idempotency-Key': key,
    'Content-Type': 'application/json',                       // otherwise text/plain;charset=UTF-8
  },
  body: JSON.stringify({ productId: 7, quantity: 2 }),
});
console.log(response.status, response.headers.get('Location'));

The order that arrived empty

Spot the bugPosting an order as JSON

Tap the line with the bug.

val body = Json.encodeToString(order)
val request = Request.Builder()
    .url("https://api.shop.example/api/orders")
    .header("Authorization", "Bearer $token")
    .post(body.toRequestBody())
    .build()
String body = mapper.writeValueAsString(order);
HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.shop.example/api/orders"))
        .header("Authorization", "Bearer " + token)
        .POST(HttpRequest.BodyPublishers.ofString(body))
        .build();
const response = await fetch('https://api.shop.example/api/orders', {
  method: 'POST',
  headers: { 'Authorization': `Bearer ${token}` },
  body: JSON.stringify(order),
});

Deep diveContent-Length, chunked encoding and request smugglingInterview favorite

An HTTP/1.1 request’s body ends either after Content-Length bytes or at the final zero-size chunk of Transfer-Encoding: chunked. If a request carries both, the spec says chunked wins and the message should be treated as suspicious. Front-end proxies and back-end servers that disagree about this, or that parse a malformed header differently (Transfer-Encoding : chunked, Transfer-Encoding: xchunked, duplicate Content-Length values), disagree about where the request ends.

The attack: the proxy thinks the request ends at one point and forwards everything; the back end stops earlier and treats the rest as the start of the next request on that keep-alive connection. That leftover prefix is then glued onto another user’s request. Consequences: bypassing the proxy’s access rules (the smuggled request to /admin was never checked), capturing other users’ requests including their cookies, and poisoning caches.

Defences:

  • Use the same, current HTTP implementation at both hops, or at least ones known to reject ambiguous requests (most servers now return 400 when both headers appear).
  • Use HTTP/2 end to end to the back end where possible: it has binary framing with explicit lengths. Watch out for HTTP/2-to-HTTP/1.1 downgrades at a proxy, which reintroduced the problem in some products.
  • Don’t reuse back-end connections across users if the proxy can’t guarantee clean framing, and keep proxies patched.

It’s a good senior answer because it ties a protocol detail (two ways to end a body) to a security failure that only exists because of keep-alive connections and multiple hops.

  • Host required; Content-Type decides parsing (no type: 415 or an empty body); Content-Length or chunked frames HTTP/1.1 bodies.
  • Negotiation with Accept* plus Vary; Brotli/zstd/gzip, not for compressed media; BREACH for secrets in compressed TLS responses.
  • Header size limits (431); HTTP/2+ lowercase names and pseudo-headers; Forwarded/X-Forwarded-For only from your own proxies.
  • Conflicting CL/TE parsing between hops = request smuggling; reject ambiguity, HTTP/2 to the back end.
curl -s -o /dev/null -w '%{size_download}\n' https://site/              # uncompressed size
curl -s -o /dev/null -w '%{size_download}\n' --compressed https://site/ # compressed size
curl -v -H 'Content-Type: application/json' -d '{"a":1}' https://api/x

Check this part

  1. Which header tells the server that the body is JSON?

  2. Are Content-Type and content-type different headers?

  3. Users with many cookies get a bare 400 from the proxy before the app sees the request. Why?

  4. What makes HTTP request smuggling possible?

Headers carry metadata: Host picks the site, Content-Type and Content-Length describe the body, Accept and Accept-Encoding negotiate the format and compression, Authorization carries credentials, Location and Retry-After guide the client. Names are case-insensitive. A JSON body without Content-Type is sent as text/plain or nothing, and many servers then ignore it.

Key takeaways

  • Requests: method, path, headers, body. Responses: status code, headers, body.
  • GET reads and must not change anything; POST isn’t idempotent, PUT and DELETE are.
  • 2xx worked, 4xx the request is wrong, 5xx the server failed. 401 = log in, 403 = not allowed.
  • Content-Type tells the server how to read the body; send application/json with JSON.
  • Libraries handle compression; curl needs --compressed.
  • Idempotency keys make POST retryable; only idempotent requests are retried automatically.
  • 307/308 keep the method; 302 turns POST into GET.
  • 502/503/504 point at different hops; timeouts decrease inward, retries at one layer.
  • RFC 9457 problem details; no 200-with-error.
  • Body framing disagreements between hops enable request smuggling.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.