HTTP messages: requests, responses, and status codes

HTTP is the application protocol of the web. A client sends a request and a server sends a response. In HTTP/1.1 these messages are plain text. A request starts with a request line, which has a method, a target, and a version. A response starts with a status line that has the version, a numeric status code, and a reason phrase. Header lines follow, then an empty line, then an optional body.

Python
request = "\r\n".join(["GET /index.html HTTP/1.1", "Host: example.com", "Accept: text/html", "", ""])
response = "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 5\r\n\r\nhello"


def parse_response(text):
    head, body = text.split("\r\n\r\n", 1)
    status_line, *header_lines = head.split("\r\n")
    version, status, reason = status_line.split(" ", 2)
    headers = {}
    for line in header_lines:
        name, value = line.split(":", 1)
        headers[name.strip().lower()] = value.strip()
    return int(status), reason, headers, body


method, target, version = request.split("\r\n")[0].split(" ")
print(method, target, version)
status, reason, headers, body = parse_response(response)
print(status, reason)
print(headers["content-length"], len(body.encode()))
print(body)
Read the full lesson