HTTP/1.1
HTTP (HyperText Transfer Protocol) is how browsers, apps and APIs request resources from servers. HTTP/1.1 (RFC 9112) is a text protocol: you can read every request and response, and even type one by hand. A client sends a request, the server sends back a response, usually over a TCP connection to port 80 (or 443 with TLS for HTTPS).
A request
GET /products?id=42 HTTP/1.1\r\n
Host: shop.example.com\r\n
User-Agent: curl/8.9.1\r\n
Accept: application/json\r\n
\r\n- The request line: method, target (path + query), version.
- Headers:
Name: valuelines.Hostis mandatory in HTTP/1.1, because one IP address can host many sites. - An empty line (
\r\n\r\n) ends the headers. - An optional body follows (for POST/PUT), whose size is given by
Content-Lengthor chunked encoding.
Parsing a request
from urllib.parse import urlsplit, parse_qs
raw = (b"POST /api/orders?debug=1 HTTP/1.1\r\n"
b"Host: shop.example.com\r\n"
b"Content-Type: application/json\r\n"
b"Content-Length: 25\r\n"
b"Connection: keep-alive\r\n"
b"\r\n"
b'{"product": 42, "qty": 3}'
b"GET /api/cart HTTP/1.1\r\n") # the next request on the same connection
def parse_request(data):
head, _, body = data.partition(b"\r\n\r\n")
lines = head.decode("iso-8859-1").split("\r\n")
method, target, version = lines[0].split(" ")
headers = {}
for line in lines[1:]:
name, _, value = line.partition(":")
headers[name.strip().lower()] = value.strip() # header names are case-insensitive
length = int(headers.get("content-length", 0))
url = urlsplit(target)
return method, url.path, parse_qs(url.query), version, headers, body[:length]
method, path, query, version, headers, body = parse_request(raw)
print(method, path, query, version)
for name, value in headers.items():
print(f" {name}: {value}")
print("body:", body)
print("left in the buffer:", raw[raw.index(b"\r\n\r\n") + 4 + len(body):])POST /api/orders {'debug': ['1']} HTTP/1.1
host: shop.example.com
content-type: application/json
content-length: 25
connection: keep-alive
body: b'{"product": 42, "qty": 3}'
left in the buffer: b'GET /api/cart HTTP/1.1\r\n'
Note that Content-Length: 25 decides where the body ends, not the end of the data that happened to arrive. That matters on a keep-alive connection, where the next request follows immediately in the same byte stream.
A response
def build_response(status, reason, body, content_type="text/html; charset=utf-8", extra=None):
payload = body.encode("utf-8")
headers = {"Content-Type": content_type, "Content-Length": str(len(payload)),
"Cache-Control": "max-age=60", **(extra or {})}
head = f"HTTP/1.1 {status} {reason}\r\n" + "".join(f"{k}: {v}\r\n" for k, v in headers.items())
return head.encode("ascii") + b"\r\n" + payload
resp = build_response(200, "OK", "<h1>Xin chào!</h1>")
print(resp.decode("utf-8"))
print("---")
print(len(resp), "bytes in total;", resp.index(b"\r\n\r\n") + 4, "bytes of headers")HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 19
Cache-Control: max-age=60
<h1>Xin chào!</h1>
---
125 bytes in total; 106 bytes of headers
Content-Length counts bytes, not characters: "Xin chào!" has 9 characters but à takes 2 bytes in UTF-8.
Methods and status codes
| Method | Meaning | Safe? | Idempotent? |
|---|---|---|---|
| GET | read a resource | yes | yes |
| HEAD | like GET, headers only | yes | yes |
| POST | create / submit / process | no | no |
| PUT | replace a resource | no | yes |
| PATCH | modify part of a resource | no | no |
| DELETE | remove a resource | no | yes |
| OPTIONS | which methods are allowed (CORS preflight) | yes | yes |
STATUS = {
200: "OK", 201: "Created", 204: "No Content",
301: "Moved Permanently", 302: "Found", 304: "Not Modified",
400: "Bad Request", 401: "Unauthorized", 403: "Forbidden", 404: "Not Found", 429: "Too Many Requests",
500: "Internal Server Error", 502: "Bad Gateway", 503: "Service Unavailable", 504: "Gateway Timeout",
}
CLASSES = {1: "informational", 2: "success", 3: "redirection", 4: "client error", 5: "server error"}
for code, reason in STATUS.items():
print(f"{code} {reason:<22} {CLASSES[code // 100]}")200 OK success
201 Created success
204 No Content success
301 Moved Permanently redirection
302 Found redirection
304 Not Modified redirection
400 Bad Request client error
401 Unauthorized client error
403 Forbidden client error
404 Not Found client error
429 Too Many Requests client error
500 Internal Server Error server error
502 Bad Gateway server error
503 Service Unavailable server error
504 Gateway Timeout server error
Tip: 502 and 504 come from a proxy or load balancer in front of your app: "the upstream server gave a bad answer / didn't answer in time". When you see them, look at the app server behind the proxy, not the proxy itself.
Chunked transfer encoding
When a server doesn't know the size of the body in advance (streaming output), it sends Transfer-Encoding: chunked: each chunk is preceded by its size in hex, and a zero-size chunk ends the body.
def decode_chunked(data):
body, pos = b"", 0
while True:
line_end = data.index(b"\r\n", pos)
size = int(data[pos:line_end], 16)
if size == 0:
return body
start = line_end + 2
body += data[start:start + size]
pos = start + size + 2 # skip the chunk's trailing \r\n
chunked = b"7\r\nNetwork\r\n1\r\n \r\nb\r\nprogramming\r\n0\r\n\r\n"
print(decode_chunked(chunked))b'Network programming'
Persistent connections
HTTP/1.0 opened a new TCP connection per request. HTTP/1.1 keeps the connection open by default (keep-alive), saving a handshake (and a TLS handshake) for every request. But requests on one connection are still answered one at a time, in order: a slow response blocks the ones behind it (head-of-line blocking). Browsers work around it by opening up to 6 connections per host. HTTP/2 fixes it properly, as you'll see in the next lesson.
rtt_ms = 50
resources = 30
handshake = rtt_ms # TCP
tls = rtt_ms # TLS 1.3
new_conn_each = resources * (handshake + tls + rtt_ms)
keep_alive = handshake + tls + resources * rtt_ms
six_parallel = handshake + tls + -(-resources // 6) * rtt_ms
print(f"new connection per request: {new_conn_each} ms")
print(f"one keep-alive connection: {keep_alive} ms")
print(f"six keep-alive connections: {six_parallel} ms")new connection per request: 4500 ms
one keep-alive connection: 1600 ms
six keep-alive connections: 350 ms
Watching HTTP with curl
curl -v http://example.com/Sample output:
* Trying 93.184.215.14:80...
* Connected to example.com (93.184.215.14) port 80
> GET / HTTP/1.1
> Host: example.com
> User-Agent: curl/8.9.1
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: text/html; charset=UTF-8
< Content-Length: 1256
< Cache-Control: max-age=604800
< Date: Sat, 17 Oct 2026 10:40:12 GMT
<
<!doctype html>
...Lines starting with > are what curl sent; < lines are what the server answered. You can also speak HTTP by hand: nc example.com 80, then type the request line, the Host: header and an empty line.
Test yourself
Which header is mandatory in every HTTP/1.1 request?
- User-Agent
- Accept
- Host
- Content-Length
What marks the end of the HTTP headers?
- A zero byte
- An empty line (\r\n\r\n)
- The Content-Length header
- Closing the connection
A proxy returns 504 Gateway Timeout. Where is the problem most likely?
- In the browser
- In the DNS server
- In the upstream application server behind the proxy
- In the user's Wi-Fi