![]() |
VOOZH | about |
We are given a scenario where we use the Python requests library to make HTTP calls, and we want to check if any error occurred during the request. This can be done using the raise_for_status() method on the response object. For example, if we request a page that doesn't exist, this method will raise an error instead of silently failing. Here's an example:
If the URL is invalid or returns a 4xx/5xx status code, it raises an HTTPError.
The raise_for_status() method belongs to the Response object in the requests library. It checks the HTTP status code of the response:
In this example, we make two requests: one to a valid API endpoint and one to a non-existent page. The first request to GitHub succeeds, so raise_for_status() does nothing. The second request fails with a 404 error, and raise_for_status() raises an HTTPError.
Output:
Success!
Traceback (most recent call last):
...
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://www.geeksforgeeks.org/naveen/
This approach is helpful during development when you want to catch issues immediately and avoid silent failures.
This example demonstrates how to use raise_for_status() with a try-except block. If an error occurs, it catches and prints a helpful message instead of crashing the program.
Output:
HTTP error occurred: 404 Client Error: Not Found for url: https://example.com/bad-url
This method is best for production code or applications that need to continue running even when a request fails. It allows you to handle errors cleanly and inform the user or log them.
Now that we've seen how raise_for_status() works both directly and inside try-except, let’s explore the specific scenarios where this method is most useful.