Open In App

response.raise_for_status() - Python requests

Last Updated : 20 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

Python
import requests

res = requests.get('https://example.com/invalid')
res.raise_for_status()


If the URL is invalid or returns a 4xx/5xx status code, it raises an HTTPError.

What is response.raise_for_status()?

The raise_for_status() method belongs to the Response object in the requests library. It checks the HTTP status code of the response:

  • If it's between 200–299 (successful responses), the method does nothing.
  • If it's a 4xx (client error) or 5xx (server error), it raises an HTTPError with details of the failed request.

Why Use raise_for_status()?

  • Prevents your program from silently continuing when something goes wrong.
  • Forces you to deal with bad responses early, which is ideal for debugging and reliability.
  • Makes error handling more structured and consistent.

Example

Example 1: Handling Valid and Invalid URLs

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.

Python
import requests

# Valid request
res = requests.get('https://api.github.com/')
res.raise_for_status()
print("Success!")

# Invalid request
res = requests.get('https://geeksforgeeks.org/naveen/')
res.raise_for_status()

Output:

Success!
Traceback (most recent call last):
...
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://geeksforgeeks.org/naveen/

This approach is helpful during development when you want to catch issues immediately and avoid silent failures.

Example 2: Graceful Error Handling with try-except

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.

Python
import requests

try:
    res = requests.get('https://example.com/bad-url')
    res.raise_for_status()
except requests.exceptions.HTTPError as e:
    print("HTTP error occurred:", e)
except requests.exceptions.RequestException as e:
    print("A request error occurred:", e)

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.

When Should You Use raise_for_status()?

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.

  • When you're fetching data from APIs
  • When you want to log errors cleanly
  • When you expect a 200 OK and treat anything else as failure
  • Not ideal if you're intentionally testing response codes (use response.status_code instead)

Next Article
Article Tags :
Practice Tags :

Similar Reads