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:
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:
OK
By default, the function will return the HTTP status code as shown:
response = requests.get('https://geekbits.io')
print(response)
Resulting output is as shown:
<Response [200]>
Example 2
The example below shows the corresponding message for a 404 error.
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:
<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.