Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
network
communitycreator

What is HTTP response in Python?

Mohammad Razi ul Haq

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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)

RELATED TAGS

python
network
communitycreator

CONTRIBUTOR

Mohammad Razi ul Haq

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring