python requests raise_for_status

Python Requests raise_for_status

Python Requests is a popular library that simplifies the process of making HTTP requests in Python. One important feature of the Requests library is the raise_for_status method, which can be used to check whether a response from an HTTP request was successful or not.

Usage

The raise_for_status method is called on a response object from an HTTP request. If the response status code indicates a successful request (i.e. a code in the 200 range), then nothing happens and the program continues to run normally. However, if the response status code indicates an error (i.e. a code in the 400 or 500 range), then a HTTPError exception is raised.

The HTTPError exception provides information about the error, including the status code and any error messages that were returned by the server.

Example


import requests

response = requests.get("https://www.example.com")

# Check if the request was successful
response.raise_for_status()

# Print the content of the response
print(response.content)

In this example, we use the get method from the Requests library to make an HTTP GET request to "https://www.example.com". We then call the raise_for_status method to check if the request was successful. If it was, we print the content of the response using the content attribute of the response object.

Alternative Method

Another way to check the status of an HTTP request is to manually check the status code using the status_code attribute of the response object. For example:


import requests

response = requests.get("https://www.example.com")

# Check if the request was successful
if response.status_code == 200:
    print(response.content)
else:
    print("Error:", response.status_code)

This method works in a similar way to using raise_for_status, but requires more code and doesn't provide as much information about the error.