Status line, headers & body

Read an HTTP response

Lesson 14 of 20 · 11 min · Module 4: Names and the web

Under every web page is plain text. An HTTP response is a status line, a set of headers, an empty line, and the body.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Describe the structure of an HTTP response
  • Split text at the first separator
  • Normalise case-insensitive header names

The idea

Lines end with "\r\n". The first line looks like HTTP/1.1 404 Not Found. Each header is Name: value, and header names are case-insensitive. The first empty line ("\r\n\r\n") separates the headers from the body.

raw = "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nhello"
head, body = raw.split("\r\n\r\n", 1)
print(head.split("\r\n"))

01Head, blank line, body

Everything before the first empty line is the head: the status line and the headers. Everything after it is the body, which may itself contain empty lines.

02Split only as much as needed

split(" ", 2) splits at most twice, so "HTTP/1.1 404 Not Found" becomes three parts with "Not Found" intact. partition(":") splits a header at its first colon, keeping https://… whole.

print("HTTP/1.1 404 Not Found".split(" ", 2))
Output
['HTTP/1.1', '404', 'Not Found']

03Header names ignore case

Content-Type, content-type, and CONTENT-TYPE are the same header. Lowercasing names when parsing makes every later lookup simple.

Your turn

Write parse_response(raw) that returns a dict with status (an int), reason, headers (a dict with lowercase names and values without surrounding spaces), and body. Header values may contain colons.

What the checks look for

  • Parses status, reason and body
  • Keeps multi-word reasons
  • Lowercases header names and keeps colons in values
  • Keeps blank lines inside the body
Try it in the editor →

Take this with you

Parse protocols by their structure: first line, headers, blank line, body.

Go a little further

Use the content-length header, when present, to check that the body has the declared length.

Learn Networking Foundations for free

20 short lessons with real code and instant checks.

See the whole course →