What is HTTP response in Python?

The HyperText Transfer Protocol(HTTP) is an application-layer protocol used to transmit hypermedia documents (such as HTML).

The request module in Python is used to make HTTP requests to web pages. A web server usually sends an HTTP response back when it receives a request. The HTTP response comprises of status code, content, and encodings.

The HTTP response has several components. Each of these components can be accessed using their specific functions.

Some of these components and their corresponding functions are:

Status code

A status code informs us of the status of a request. It tells us whether the response was successfully received(Status code 200), whether the content was not found(Status code 404), or any other information the status code returned. We can access the status code using the response.status_code function.

Content

The content contains the actual message/data returned from the server. There are several methods that can be used to access this data:

  • response.content: displays the byte formatted response.
  • response.text: displays the content in text format.
  • response.json: displays the content in JSON format.

Headers

The response.header method allows us to view the headers of the response. These headers contain important information such as the Server name, the encoding of the response, etc.

The following code demonstrates how to get the various components of an HTTP response.

import requests
response = requests.get("http://www.google.com")
print("Response code:", response.status_code)
print("Response formatted as text:",response.text)
print("Response formatted in bytes:",response.content)
print("Response Headers:",response.headers)