Python Responses

Learn via video course
FREE
View all courses
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Topics Covered

Overview

Python Responses are a persuasive object that provides multiple functionalities and attributes that helps to normalize data and to create the code's ideal portions. Whenever a URL request is made it would return a response. In terms of python the response object is returned by the requests.method() irrespective of whether it is GET, POST, PUT, etc.

When one makes a request to a URI, it returns a response. This Response object in terms of python is returned by requests.method(), method being – get, post, put, etc. The response is a powerful object with lots of functions and attributes that assist in normalizing data or creating ideal portions of code.

Python Response Methods in Requests

As discussed earlier, Python Responses aids us with different features and attributes that help to normalize data and to create the code's ideal portions. It provides us with multiple response methods that can be used to achieve the mentioned. The Python Response method aids us with multiple features, functionalities, and methods.

For example, In the given case below, the response.status_code will return the header's status code thus allowing us to check the success or failure status of the processed request.

Code:

The above file can be saved as follows:

Output:

output response status code

The above code will display the output with a status code of 200, referring that the request that has been made successfully.

Python Response

Following are some common Python Responses methods in requests:

MethodDescription
response.headersreturns a dictionary of response headers.
response.encodingreturns the encoding used to decode the response.content.
response.elapsedreturns a time delta object with the time elapsed from sending the request to the arrival of the response.
response.close()closes the connection to the server.
response.contentreturns the content of the response, in bytes.
response.cookiesreturns a CookieJar object with the cookies sent back from the server.
response.historyreturns a list of response objects holding the history of the request (url).
response.is_permanent_redirectreturns True if the response is the permanently redirected url, otherwise False.
response.is_redirectreturns True if the response was redirected, otherwise False.
response.iter_content()iterates over the response.content.
response.json()returns a JSON object of the result (if the result was written in JSON format, if not it raises an error).
response.urlreturns the URL of the response.
response.textreturns the content of the response, in Unicode.
response.status_codereturns a number that indicates the status (200 is OK, 404 is Not Found).
response.requestreturns the request object that requested this response.
response.reasonreturns a text corresponding to the status code.
response.raise_for_status()returns an HTTPError object if an error has occurred during the process.
response.okreturns True if status_code is less than 200, otherwise False.
response.linksreturns the header links.

Most Used Python Response Methods

In this section we will learn about some of the most used Python Responses methods:

Response.json()

The response.json() method is used to return the JSON object of the obtained result from the event. In order to use this method, the result must be in the JSON format otherwise the response.json() will display an error.

Using the response.json() method with Python requests:

Now that we know what the response.json() method is, let us learn how to use the response.json() method with Python requests.

Code:

Output:

output response json method with python request

Explanation of the example:

In the above example, we are importing the requests module to trigger the get request. The requests.get() method will GET the data from 'https://reqres.in/api/users?page=2' and store the response in res. The print(res) will display the status code 200 indicating that the request had been made successfully. The print(res.json()) will display the JSON data.

Response.ok

The response.ok method is a read-only method that returns a boolean value stating whether the response of the request was successful or not. If the status code is less than or equal to then the response.ok will return true otherwise it will return false.

Using the response.ok method with Python requests:

Now that we know what the response.ok method is, let us learn how to use the response.ok method with Python requests.

Code:

Output:

output response ok code

Explanation of the example:

In the above example, we are importing the requests module to trigger the get request. The requests.get() method will GET the data from 'https://reqres.in/api/users?page=2' and store the response in res. The print(res) will display the status code 200 indicating that the request had been made successfully. The print(res.ok) will show the true since the value of the status code is 200 which is less than or equal to 200.

Response.status_code

The response.status_code method in Python Responses is used to return a numeric value that indicates the status of the request that has been made. Every status code has a distinct memo associated with it, for e.g. status code 200 means that the response is OK and the status code 404 means that there is an error.

Using the response.status_code method with Python requests:

Now that we know what the response.status_code method is, let us learn how to use the response.status_code method with Python requests.

Code:

Output:

output response status code method

Explanation of the example:

In the above example, we are importing the requests module to trigger the get request. The requests.get() method will GET the data from 'https://reqres.in/api/users?page=2' and store the response in res. The print(res.status_code) will display the status code 200 indicating that the request had been made successfully.

Response.content

The response.content method in Python Responses is used to return the byte response result from the event. Basically the response.content is used to display binary response content.

Using the response.content method with Python requests:

Now that we know what the response.content method is, let us learn how to use the response.content method with Python requests.

Code:

Output:

output response content method

Explanation of the example:

In the above example, we are importing the requests module to trigger the get request. The requests.get() method will GET the data from 'https://reqres.in/api/users?page=2' and store the response in res. The print(res) will display the status code 200 indicating that the request had been made successfully. The print(res.content) will display the byte data.

What is a Python Response Object?

Whenever a request is made to a URI, It would return a response object. In Python terms, this object is returned by the requests.method() method. The methods can be GET, POST, GET, PUT, etc.

The Python Response Object helps us in sending any response with respect to client requests. The Python Response Object consists of many predefined methods, functionalities, etc.

What is Response Type in Python?

The Response Type in Python Responses refers to the value that specifies the datatype that has been contained by the Python Response Object. In order to check the response type in Python, we can look for the Content-Type header for the response object. The Content-Type Header is used to tell what kind of body the response object represents.

How to Create a Response Object in Python?

Now that we've learned what is Python Responses Object, In this section, we will learn how to create a Python Response Object. In order to create a Python Response Object, we need to follow the given steps:

  • Step 1: Import Response from the 'requests.models' module in your Python program.
  • Step 2: Call Response() method and store it in res.
  • Step 3: Assign the string value "expired" to the res.code.
  • Step 4: Similarly, assign the string value "expired" to the res.error_type.
  • Step 5: Assign the value 400 to the res.status_code.
  • Step 6: Give the object with "a" as "key" value to res._content.
  • Step 7: Display the response.

Code:

Output:

output res content method

How to Get Python Response API?

In this section, we will learn how to GET Python Responses using an API. In order to get Python Responses, we need to follow the following steps:

  • Step 1: In this step, we will define a function and will pass the API as the parameter.
  • Step 2: In this step, we will use the requests.get() method to call the API. This will fetch us the API response which will be stored in res.
  • Step 3: In this step, we will add conditions to the response according to it's status code (i.e. if the status code is 200, then we will display the response otherwise we will tell the user that there is an error).

Output:

output get python responses

Examples for Understanding

In this section we will go through some examples to understand the working of Python Responses:

Fetching the Data of A User Using Python Response

In this example, we will fetch the data of a random person using Python Requests.

Code:

Output:

output fetching data of user using python response

Explanation of the output:

In the above example, we have imported the requests module. The requests.get('https://reqres.in/api/users/2') will fetch the data for the user and store it in res. Thus the print(res.json()) will display the user data and the status 200 will indicate that the response has been successful.

Conclusion

  • Python Responses provide multiple functionalities and attributes that help to normalize data and to create the code's ideal portions.
  • Python Responses object is returned by the requests.method() irrespective of whether it is GET, POST, PUT, etc.
  • The response.json() method is used to return the JSON object of the obtained result from the event.
  • The response.status_code method is used to return a numeric value that indicates the status of the request that has been made.
  • The response.ok method is a read-only method that returns a boolean value stating whether the response of the request was successful or not.
  • The response.content method is used to return the byte response result from the event.
  • The status code 200 means that the response is OK.
  • The status code 404 means that there is an error.
  • The Python Responses Object helps us in sending any response with respect to client requests.
  • The Response Type in Python Responses refers to the value that specifies the datatype that has been contained by the Python Response Object.
  • The Content-Type Header is used to tell what kind of body the response object represents.