raise_for_status()
is a method of the Response
object in the requests library, which is used to check the status code of the HTTP response and throw an HTTPError exception when the request fails.
How it works
When calling raise_for_status()
:
- If the response status code is a success status code between 200 and 299,
raise_for_status()
does nothing. - If the status code indicates an error (such as 4xx or 5xx), a
requests.exceptions.HTTPError
exception is raised.
Example of use
import requests
url = "https://httpbin.org/status/404" # A test URL that returns a 404
try:
response = requests.get(url)
response.raise_for_status() # If the status code is not 2xx, an HTTPError exception will be thrown
except requests.exceptions.HTTPError as err:
print(f"HTTP error occurred: {err}") # Capture and print HTTP errors
except Exception as err:
print(f"Other error occurred: {err}") # Catch and print other exceptions
else:
print("Request was successful!") # If no exception is thrown, the request is successful