Networking Tutorial · Core Protocols · Lesson 13 of 28
HTTP
The request/response protocol of the web: methods, status codes, headers, and what an HTTP message looks like.
Requests and responses
HTTP is a request/response protocol. The client sends a method, a path, headers and an optional body; the server answers with a status code, headers and a body. HTTP/1.1 messages are plain text:
GET /api/orders/42 HTTP/1.1
Host: shop.example.com
Accept: application/json
Authorization: Bearer eyJhbGciOi...
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-store
Content-Length: 28
{"id": 42, "status": "paid"}
raw = (
"HTTP/1.1 200 OK\r\n"
"Content-Type: application/json\r\n"
"Cache-Control: no-store\r\n"
"Content-Length: 28\r\n"
"\r\n"
'{"id": 42, "status": "paid"}'
)
head, body = raw.split("\r\n\r\n", 1)
status_line, *header_lines = head.split("\r\n")
version, code, reason = status_line.split(" ", 2)
headers = {k.lower(): v for k, v in (line.split(": ", 1) for line in header_lines)}
print("status:", code, reason)
print("headers:", headers)
print("body:", body)
Output
status: 200 OK
headers: {'content-type': 'application/json', 'cache-control': 'no-store', 'content-length': '28'}
body: {"id": 42, "status": "paid"}Methods
GET reads, POST creates or triggers, PUT replaces, PATCH partially updates, DELETE deletes. GET,
PUT and DELETE are idempotent: repeating them has the same effect, so clients and proxies may retry them.
Status code families
| Range | Meaning | Common codes |
|---|---|---|
| 2xx | Success | 200 OK, 201 Created, 204 No Content |
| 3xx | Redirect | 301 Moved Permanently, 302 Found, 304 Not Modified |
| 4xx | Client error | 400, 401 Unauthorized, 403 Forbidden, 404, 409 Conflict, 429 Too Many Requests |
| 5xx | Server error | 500, 502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout |
502 and 504 come from a proxy or load balancer in front of your app: 502 means it got a bad or no response (for example the app closed the connection), 504 means the app didn't answer in time.
Try it
$ curl -i https://example.com # show response headers
$ curl -v https://example.com # show the whole conversation, including TLS
Test yourself
A load balancer returns 504 to users. What does that usually mean?
The user isn't logged inThe backend didn't respond within the load balancer's timeoutThe URL doesn't existThe request body was invalid JSON
Show answer
Answer: The backend didn't respond within the load balancer's timeout
504 Gateway Timeout comes from a proxy whose upstream was too slow. Check backend latency and the timeouts on both sides.