Asserting Success via raise_for_status()
๐ท๏ธ APIs and HTTP Requests / The Requests Library
When working with APIs, you send a request and get back a response. But how do you know if that response actually succeeded? A status code like 200 means everything went well, while 404 or 500 means something went wrong. The raise_for_status() method is a simple, built-in way to check for errors and stop your program immediately if a request fails.
๐ง What Does raise_for_status() Do?
- It checks the HTTP status code of a response object.
- If the status code indicates an error (like 400, 404, 500, etc.), it automatically raises an exception.
- If the status code is successful (like 200, 201, 204), it does nothing and your code continues running.
This saves you from writing manual checks for every single request.
โ๏ธ How to Use raise_for_status()
You call raise_for_status() on the response object after making a request. Here is the basic pattern:
- Make a request using requests.get() or requests.post().
- Store the response in a variable.
- Call response.raise_for_status().
- If the request failed, the program stops and shows an error message.
- If it succeeded, your code continues to the next step.
Example flow:
Step 1: Import the requests library.
Step 2: Send a GET request to an API endpoint.
Step 3: Call response.raise_for_status() to check for errors.
Step 4: If no error, process the response data.
๐ ๏ธ Why Not Just Check the Status Code Manually?
You could write an if statement to check response.status_code, but raise_for_status() is cleaner and more reliable. Here is a comparison:
| Approach | Code Example | Behavior |
|---|---|---|
| Manual check | if response.status_code != 200: print("Error") | You must decide what to do for every possible error code. Easy to forget edge cases. |
| raise_for_status() | response.raise_for_status() | Automatically raises an exception for any error status code. No manual logic needed. |
Using raise_for_status() means you handle all error codes (not just 200) in one line.
๐ต๏ธ What Happens When an Error Occurs?
When raise_for_status() detects a failed request, it raises an HTTPError exception. This stops your program and prints a clear message showing:
- The HTTP status code (e.g., 404, 500)
- A short description of the error
You can catch this exception using a try/except block if you want to handle the error gracefully instead of crashing.
Example pattern with error handling:
Step 1: Wrap your request inside a try block.
Step 2: Call response.raise_for_status() inside the try.
Step 3: In the except block, catch the requests.exceptions.HTTPError.
Step 4: Print a friendly error message or take alternative action.
๐ Common Status Codes That Trigger raise_for_status()
- 400 Bad Request โ The server could not understand your request.
- 401 Unauthorized โ You need to provide authentication.
- 403 Forbidden โ You do not have permission to access the resource.
- 404 Not Found โ The requested URL does not exist.
- 500 Internal Server Error โ Something went wrong on the server side.
- 502 Bad Gateway โ The server received an invalid response from another server.
Any status code in the 400 or 500 range will cause raise_for_status() to raise an error.
โ Best Practices for Engineers
- Always call raise_for_status() after every request to catch failures early.
- Use a try/except block when you want to log errors or retry failed requests.
- Do not rely on checking response.ok (a boolean property) alone โ raise_for_status() gives you more detailed error information.
- Combine raise_for_status() with timeout settings to handle slow or unresponsive APIs.
๐งช Quick Reference
- response.raise_for_status() โ Checks if the request succeeded. Raises an error if not.
- requests.exceptions.HTTPError โ The exception type raised for failed requests.
- try/except โ Use this to catch the error and handle it without crashing your program.
By using raise_for_status(), you write cleaner, safer code that fails fast and gives you clear feedback when something goes wrong with your API calls.
The raise_for_status() method checks if an HTTP request returned an error status code and raises an exception if it did, so you can stop execution instead of working with bad data.
๐ข Example 1: Basic successful request with raise_for_status()
This example shows what happens when a request succeeds โ no error is raised.
import requests
response = requests.get("https://httpbin.org/status/200")
response.raise_for_status()
print("Request succeeded")
๐ค Output: Request succeeded
๐ด Example 2: Detecting a 404 error
This example shows raise_for_status() raising an exception when a page is not found.
import requests
response = requests.get("https://httpbin.org/status/404")
try:
response.raise_for_status()
except requests.exceptions.HTTPError as error:
print(f"Error caught: {error}")
๐ค Output: Error caught: 404 Client Error: NOT FOUND for url: https://httpbin.org/status/404
๐ Example 3: Detecting a 500 server error
This example shows raise_for_status() catching a server-side error.
import requests
response = requests.get("https://httpbin.org/status/500")
try:
response.raise_for_status()
except requests.exceptions.HTTPError as error:
print(f"Server error: {error}")
๐ค Output: Server error: 500 Server Error: INTERNAL SERVER ERROR for url: https://httpbin.org/status/500
โ Example 4: Using raise_for_status() before accessing data
This example shows how to guard your code so you only process data when the request succeeded.
import requests
response = requests.get("https://httpbin.org/json")
try:
response.raise_for_status()
data = response.json()
print("Data received successfully")
print(data["slideshow"]["title"])
except requests.exceptions.HTTPError as error:
print(f"Failed to get data: {error}")
๐ค Output: Data received successfully
๐ค Output: Slide Show
๐ Example 5: Checking multiple endpoints in a loop
This example shows how to use raise_for_status() when checking several URLs in a loop.
import requests
urls = [
"https://httpbin.org/status/200",
"https://httpbin.org/status/404",
"https://httpbin.org/status/500"
]
for url in urls:
response = requests.get(url)
try:
response.raise_for_status()
print(f"{url} - OK")
except requests.exceptions.HTTPError as error:
print(f"{url} - FAILED: {error}")
๐ค Output: https://httpbin.org/status/200 - OK
๐ค Output: https://httpbin.org/status/404 - FAILED: 404 Client Error: NOT FOUND for url: https://httpbin.org/status/404
๐ค Output: https://httpbin.org/status/500 - FAILED: 500 Server Error: INTERNAL SERVER ERROR for url: https://httpbin.org/status/500
Comparison Table
| Scenario | Without raise_for_status() |
With raise_for_status() |
|---|---|---|
| Successful request (200) | Code continues normally | Code continues normally |
| Client error (404) | Code continues with bad data | Exception is raised, error is caught |
| Server error (500) | Code continues with bad data | Exception is raised, error is caught |
| Accessing response data | May crash on invalid data | Safe โ only runs after success check |
When working with APIs, you send a request and get back a response. But how do you know if that response actually succeeded? A status code like 200 means everything went well, while 404 or 500 means something went wrong. The raise_for_status() method is a simple, built-in way to check for errors and stop your program immediately if a request fails.
๐ง What Does raise_for_status() Do?
- It checks the HTTP status code of a response object.
- If the status code indicates an error (like 400, 404, 500, etc.), it automatically raises an exception.
- If the status code is successful (like 200, 201, 204), it does nothing and your code continues running.
This saves you from writing manual checks for every single request.
โ๏ธ How to Use raise_for_status()
You call raise_for_status() on the response object after making a request. Here is the basic pattern:
- Make a request using requests.get() or requests.post().
- Store the response in a variable.
- Call response.raise_for_status().
- If the request failed, the program stops and shows an error message.
- If it succeeded, your code continues to the next step.
Example flow:
Step 1: Import the requests library.
Step 2: Send a GET request to an API endpoint.
Step 3: Call response.raise_for_status() to check for errors.
Step 4: If no error, process the response data.
๐ ๏ธ Why Not Just Check the Status Code Manually?
You could write an if statement to check response.status_code, but raise_for_status() is cleaner and more reliable. Here is a comparison:
| Approach | Code Example | Behavior |
|---|---|---|
| Manual check | if response.status_code != 200: print("Error") | You must decide what to do for every possible error code. Easy to forget edge cases. |
| raise_for_status() | response.raise_for_status() | Automatically raises an exception for any error status code. No manual logic needed. |
Using raise_for_status() means you handle all error codes (not just 200) in one line.
๐ต๏ธ What Happens When an Error Occurs?
When raise_for_status() detects a failed request, it raises an HTTPError exception. This stops your program and prints a clear message showing:
- The HTTP status code (e.g., 404, 500)
- A short description of the error
You can catch this exception using a try/except block if you want to handle the error gracefully instead of crashing.
Example pattern with error handling:
Step 1: Wrap your request inside a try block.
Step 2: Call response.raise_for_status() inside the try.
Step 3: In the except block, catch the requests.exceptions.HTTPError.
Step 4: Print a friendly error message or take alternative action.
๐ Common Status Codes That Trigger raise_for_status()
- 400 Bad Request โ The server could not understand your request.
- 401 Unauthorized โ You need to provide authentication.
- 403 Forbidden โ You do not have permission to access the resource.
- 404 Not Found โ The requested URL does not exist.
- 500 Internal Server Error โ Something went wrong on the server side.
- 502 Bad Gateway โ The server received an invalid response from another server.
Any status code in the 400 or 500 range will cause raise_for_status() to raise an error.
โ Best Practices for Engineers
- Always call raise_for_status() after every request to catch failures early.
- Use a try/except block when you want to log errors or retry failed requests.
- Do not rely on checking response.ok (a boolean property) alone โ raise_for_status() gives you more detailed error information.
- Combine raise_for_status() with timeout settings to handle slow or unresponsive APIs.
๐งช Quick Reference
- response.raise_for_status() โ Checks if the request succeeded. Raises an error if not.
- requests.exceptions.HTTPError โ The exception type raised for failed requests.
- try/except โ Use this to catch the error and handle it without crashing your program.
By using raise_for_status(), you write cleaner, safer code that fails fast and gives you clear feedback when something goes wrong with your API calls.
Interactive Views
You are currently in ๐ All-in-One mode. Use the tabs at the top to switch to ๐ Theory Only or ๐ป Code Only views.
The raise_for_status() method checks if an HTTP request returned an error status code and raises an exception if it did, so you can stop execution instead of working with bad data.
๐ข Example 1: Basic successful request with raise_for_status()
This example shows what happens when a request succeeds โ no error is raised.
import requests
response = requests.get("https://httpbin.org/status/200")
response.raise_for_status()
print("Request succeeded")
๐ค Output: Request succeeded
๐ด Example 2: Detecting a 404 error
This example shows raise_for_status() raising an exception when a page is not found.
import requests
response = requests.get("https://httpbin.org/status/404")
try:
response.raise_for_status()
except requests.exceptions.HTTPError as error:
print(f"Error caught: {error}")
๐ค Output: Error caught: 404 Client Error: NOT FOUND for url: https://httpbin.org/status/404
๐ Example 3: Detecting a 500 server error
This example shows raise_for_status() catching a server-side error.
import requests
response = requests.get("https://httpbin.org/status/500")
try:
response.raise_for_status()
except requests.exceptions.HTTPError as error:
print(f"Server error: {error}")
๐ค Output: Server error: 500 Server Error: INTERNAL SERVER ERROR for url: https://httpbin.org/status/500
โ Example 4: Using raise_for_status() before accessing data
This example shows how to guard your code so you only process data when the request succeeded.
import requests
response = requests.get("https://httpbin.org/json")
try:
response.raise_for_status()
data = response.json()
print("Data received successfully")
print(data["slideshow"]["title"])
except requests.exceptions.HTTPError as error:
print(f"Failed to get data: {error}")
๐ค Output: Data received successfully
๐ค Output: Slide Show
๐ Example 5: Checking multiple endpoints in a loop
This example shows how to use raise_for_status() when checking several URLs in a loop.
import requests
urls = [
"https://httpbin.org/status/200",
"https://httpbin.org/status/404",
"https://httpbin.org/status/500"
]
for url in urls:
response = requests.get(url)
try:
response.raise_for_status()
print(f"{url} - OK")
except requests.exceptions.HTTPError as error:
print(f"{url} - FAILED: {error}")
๐ค Output: https://httpbin.org/status/200 - OK
๐ค Output: https://httpbin.org/status/404 - FAILED: 404 Client Error: NOT FOUND for url: https://httpbin.org/status/404
๐ค Output: https://httpbin.org/status/500 - FAILED: 500 Server Error: INTERNAL SERVER ERROR for url: https://httpbin.org/status/500
Comparison Table
| Scenario | Without raise_for_status() |
With raise_for_status() |
|---|---|---|
| Successful request (200) | Code continues normally | Code continues normally |
| Client error (404) | Code continues with bad data | Exception is raised, error is caught |
| Server error (500) | Code continues with bad data | Exception is raised, error is caught |
| Accessing response data | May crash on invalid data | Safe โ only runs after success check |