Interpret HTTP Methods, Statuses and Headers
Core idea
An HTTP request carries a method, target, headers and possibly a body. A response carries a status, headers and possibly a body. Request objects can be prepared without sending them. HTTPResponse can parse a local byte stream; the examples use a synthetic socket adapter instead of a network connection.
from urllib.request import Requestr = Request('https://api.example/items', data=b'{"qty":2}', headers={'Content-Type':'application/json'}, method='POST')print(r.get_method())print(r.get_header('Content-type'))print(r.data.decode())No request is sent; bytes and content type are set explicitly.
Parse a synthetic response
from http.client import HTTPResponsefrom io import BytesIOclass FixtureSocket: def makefile(self, *args, **kwargs): return BytesIO(b'HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ndone')with HTTPResponse(FixtureSocket()) as response: response.begin() print(response.status, response.getheader('Content-Length')) print(response.read().decode())begin reads the status and headers; read consumes the declared body.
Common mistake
A successful HTTP status does not guarantee valid application data. Check status and content before decoding, and close response and connection resources.
Practice
Change the fixture to a 404 response with a short body and decide how a client should handle it.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTTP request and response
Check your understanding of http request and response.
What is printed?
from urllib.request import Requestprint(Request('https://example.test').get_method())What is printed?
from http import HTTPStatusprint(HTTPStatus.NO_CONTENT.value)What is a response header?
Does constructing Request send traffic?