Inside HTTP: What Actually Goes Over the Wire

Inside HTTP: What Actually Goes Over the Wire in Python: You have used . Now open the envelope.

Concept Explanation

You have used requests.get(). Now open the envelope. HTTP is not magic and it is not binary — it is plain text sent over a TCP socket, simple enough that you can type a valid request by hand.

Understanding the raw protocol is what lets you debug the problems libraries hide: why a POST returns 415, why your cookie is ignored, why a response is truncated, why the same request works in curl but not in Python.

An HTTP Request, In Full

GET /search?q=python HTTP/1.1
Host: example.com
User-Agent: MyClient/1.0
Accept: application/json
Connection: close

Four parts, in strict order:

  1. Request line — method, path (with query string), protocol version.
  2. Headers — Name: value, one per line.
  3. A blank line — this is what signals "headers are finished."
  4. Body — optional; present for POST and PUT.

Every line ends with \r\n (carriage return and line feed), not just \n. That detail matters when you write the bytes yourself.

An HTTP Response

HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 27

{"status": "ok", "id": 42}

Same shape: status line, headers, blank line, body.

Status Codes by Class

RangeMeaningYou should
1xxInformationalRarely see these
2xxSuccessProceed (200 OK, 201 Created, 204 No Content)
3xxRedirectFollow Location (301 permanent, 302 temporary, 304 Not Modified)
4xxYour request is wrongFix the request — retrying identically will not help
5xxTheir server brokeRetry with backoff

The ones worth memorising: 401 you are not authenticated, 403 you are authenticated but not allowed, 404 no such resource, 422 the shape was valid but the values were not, 429 slow down, 500 their bug, 503 temporarily overloaded.

Headers That Cause Real Bugs

HeaderWhy it bites
HostMandatory in HTTP/1.1. One IP serves many sites; this picks which
Content-TypeSend JSON with application/x-www-form-urlencoded and you get 400 or 415
Content-LengthWrong value means a hung or truncated request
AcceptHow you ask for JSON instead of HTML
AuthorizationBearer <token> — the right place for credentials
Connectionkeep-alive reuses the socket; close ends it

Statelessness and Cookies

HTTP has no memory. Every request is independent — the server does not know request #2 came from whoever sent request #1. Cookies are the workaround: the server sends Set-Cookie, the client echoes it back in Cookie on every later request. Sessions, logins, and shopping carts are all built on that one echo.


Code Example #1 (Basic)

Speaking HTTP over a bare socket — no libraries.

import socket

host = "example.com"

# Build the request by hand. Note \r\n line endings and the blank line at the end.
request = (
    "GET / HTTP/1.1\r\n"
    f"Host: {host}\r\n"
    "User-Agent: RawSocketClient/1.0\r\n"
    "Accept: text/html\r\n"
    "Connection: close\r\n"
    "\r\n"                      # <-- the blank line ends the headers
)

with socket.create_connection((host, 80), timeout=10) as sock:
    sock.sendall(request.encode("ascii"))

    chunks = []
    while True:
        chunk = sock.recv(4096)
        if not chunk:            # server closed -- response complete
            break
        chunks.append(chunk)

raw = b"".join(chunks)
head, _, body = raw.partition(b"\r\n\r\n")

print("--- STATUS AND HEADERS ---")
print(head.decode("iso-8859-1"))
print("--- BODY (first 200 bytes) ---")
print(body[:200].decode("utf-8", errors="replace"))

That is the whole protocol. requests adds connection pooling, redirects, cookies, decompression, and encoding detection — but underneath it writes these same bytes.

Code Example #2 (Intermediate)

Reading a response the way libraries must: honouring Content-Length and chunked encoding.

import socket

def http_get(host, path="/", port=80, timeout=10):
    """A GET that parses the response properly instead of waiting for close."""
    request = (
        f"GET {path} HTTP/1.1\r\n"
        f"Host: {host}\r\n"
        "Accept-Encoding: identity\r\n"   # ask for no gzip, to keep this readable
        "Connection: close\r\n\r\n"
    )

    with socket.create_connection((host, port), timeout=timeout) as sock:
        sock.sendall(request.encode("ascii"))
        buf = b""

        # Phase 1: read until the headers are complete
        while b"\r\n\r\n" not in buf:
            chunk = sock.recv(4096)
            if not chunk:
                raise ConnectionError("Closed before headers finished")
            buf += chunk

        head, _, body = buf.partition(b"\r\n\r\n")
        lines = head.decode("iso-8859-1").split("\r\n")
        version, code, *reason = lines[0].split(" ")

        headers = {}
        for line in lines[1:]:
            name, _, value = line.partition(":")
            headers[name.strip().lower()] = value.strip()

        # Phase 2: read the body, using whatever framing the server chose
        if "content-length" in headers:
            need = int(headers["content-length"])
            while len(body) < need:
                chunk = sock.recv(4096)
                if not chunk:
                    break
                body += chunk
            body = body[:need]
        else:
            # No length given: read until close (or handle Transfer-Encoding: chunked)
            while True:
                chunk = sock.recv(4096)
                if not chunk:
                    break
                body += chunk

    return int(code), " ".join(reason), headers, body

status, reason, headers, body = http_get("example.com", "/")
print(f"{status} {reason}")
for key in ("content-type", "content-length", "server", "date"):
    if key in headers:
        print(f"  {key}: {headers[key]}")
print(f"  body bytes: {len(body)}")

Notice the two-phase read. You cannot know how much body to expect until you have parsed the headers, and you cannot parse the headers until you have found the blank line. Every HTTP client on earth does these two phases.


Common Mistakes

  1. Using \n instead of \r\n: most servers tolerate it, some reject it outright with 400. The spec says \r\n.
  2. Omitting the blank line: the server waits forever for headers that never end, and your request times out with no error message.
  3. Forgetting the Host header: mandatory in HTTP/1.1. Without it a shared-hosting server has no idea which site you want.
  4. Reading until close on a keep-alive connection: with Connection: keep-alive the server never closes, so a naive read-until-empty loop hangs. Honour Content-Length.
  5. Sending JSON with the wrong Content-Type: the body is fine, the header lies, and you get 400 or 415. Use application/json.
  6. Treating 3xx as an error: a 301 with a Location header is the server telling you exactly where to go. Follow it (and cap the number of hops).
  7. Retrying a 4xx: nothing about your request will improve on the second attempt. Retry 429 and 5xx; fix 4xx.
  8. Decoding the body as UTF-8 unconditionally: check the charset in Content-Type, and pass errors="replace" when you must guess.

Best Practices

  • Read the actual headers when debugging: curl -v or response.request.headers tells you what you really sent, which is often not what you thought.
  • Set Accept explicitly: ask for application/json rather than hoping the server's default is what you want.
  • Put credentials in Authorization, never the query string: URLs are logged by proxies, servers, and browser history.
  • Respect the status class: 4xx means change the request, 5xx means retry later, 429 means wait the stated time.
  • Prefer HTTPS always: plain HTTP on port 80 exposes headers — including your tokens — to anyone on the path.
  • Reuse connections: a requests.Session skips the handshake on every subsequent call.
  • Let a library do this in production: writing raw HTTP is how you learn the protocol, not how you ship a client. Chunked encoding, gzip, redirects, and TLS are solved problems.

Practice Exercises

  1. The Manual Request: Use the raw-socket example to fetch three different sites and print each status line and Content-Type. Then deliberately delete the Host header and record exactly what each server returns.
  2. The Status Tour: Using https://httpbin.org/status/{code}, request 200, 301, 404, 429, and 503. For each, print the status and write one line stating whether a client should retry, follow, or fix.
  3. The Header Inspector: Write a function that takes a URL and prints every response header sorted alphabetically, then flag which of Content-Length, Transfer-Encoding, or neither the server used to frame the body — and explain what your reader loop must do in each case.