response.raise_for_status() – Python requests



response.raise_for_status() – Python requests

response.raise_for_status() returns an HTTPError object if an error has occurred during the process. It is used for debugging the requests module and is an integral part of Python requests. Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.raise_for_status() out of a response object.

How to use response.raise_for_status() using Python requests?

To illustrate use of response.raise_for_status(), let’s ping github.com and geeksforgeeks.org. To run this script, you need to have Python and requests installed on your PC.

Example code –
# import requests module
import requests
 
# Making a get request
response = requests.get('https://api.github.com/')
 
# print response
print(response)
 
# print check if an error has occurred
print(response.raise_for_status())
 
# ping an incorrect url
response = requests.get('https://geeksforgeeks.org / naveen/')
 
# print check if an error has occurred
print(response.raise_for_status())
Example Implementation –

Save above file as request.py and run using

Python request.py
Output –

response.raise_for_status-Python-requests

Check that Traceback error, it shows that an error has occurred along with the error “Invalid URL” and status code 404.

Advanced Concepts

There are many libraries to make an HTTP request in Python, which are httpliburllibhttplib2treq, etc., but requests is the one of the best with cool features. If any attribute of requests shows NULL, check the status code using below attribute.

requests.status_code

If status_code doesn’t lie in range of 200-29. You probably need to check method begin used for making a request + the url you are requesting for resources.

Last Updated on November 13, 2021 by admin

Leave a Reply

Your email address will not be published. Required fields are marked *

Recommended Blogs