Parse a synthetic HTTP status line
Parse a synthetic HTTP status line
An HTTP response begins with a status line. This synthetic fixture, HTTP/1.1 404 Not Found, is deliberately handled as plain text: the code removes its CRLF terminator, splits it into exactly three parts, and checks that the protocol token and reason phrase have the expected values. Converting the middle token with int() produces the numeric status code.
http.HTTPStatus gives that integer a standard-library meaning. The assertion against HTTPStatus.NOT_FOUND checks this particular fixture is 404, while the assertion against .phrase checks that its supplied reason is the enum’s conventional phrase. HTTPStatus was added in Python 3.5; the example therefore requires Python 3.5 or later.
This is a small parser for one controlled line, not a complete HTTP response parser. It does not validate every aspect of HTTP version syntax, accept unusual whitespace, read headers, or determine whether a reason phrase is required by a particular protocol version. The assertions only establish facts about this fixture and the selected enum member. For a full response received from a peer, use an HTTP implementation that handles the complete framing rules.
Python documents HTTPStatus as an IntEnum with status codes and English phrases in the http module documentation. The conversion used here follows the int() documentation.
AI-assistance disclosure: AI assisted the drafting of this educational example.
from http import HTTPStatus
line = "HTTP/1.1 404 Not Found\r\n"
version, code_text, reason = line.rstrip("\r\n").split(" ", 2)
status = HTTPStatus(int(code_text))
assert version == "HTTP/1.1"
assert status is HTTPStatus.NOT_FOUND
assert reason == status.phrase
print(status.value, status.phrase)
404 Not Found