Python

Response.reason

In this article, you will discover what is the response.reason() function is, and how it works from the Python’s request library.

Requests response.reason() function

The reason() function from the request module is used to fetch the corresponding text description of a given HTTP status code. For example, you can use it to map the 404-status code to its corresponding HTTP message Not Found.

Using the response object from the requests module, you can determine what message the request returns.

Practical Example

To best illustrate how we can use this function, we can attempt to access a specific resource and fetch the status code and message from it.

Consider the example shown below:

import requests
response = requests.get('https://geekbits.io')
print(response.reason)

The code above makes a GET request to the specified URL and saves the response to the response object. We then fetch the HTTP description of the return code using the response.reason.

The code above should return an output as shown:

python3 test.py
OK

By default, the function will return the HTTP status code as shown:

import requests
response = requests.get('https://geekbits.io')
print(response)

Resulting output is as shown:

python3 test.py
<Response [200]>

Example 2

The example below shows the corresponding message for a 404 error.

import requests
response = requests.get('https://google.com/404')
print(response)
print(response.reason)

In this case, the code above should return the HTTP status code and the reason as shown in the output below:

python3 test.py
<Response [404]>
Not Found

Conclusion

In this article, you learned how to use the response.reason method from the requests module to resolve a HTTP status code to the corresponding message.

To learn more about HTTP status codes, check here.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list