API Navigator Logo

Python Handle 404 and 500 Errors in API

Author: Newtum

This example shows how to gracefully handle common HTTP errors like 404 (Not Found) and 500 (Internal Server Error) when interacting with APIs in Python.

Using `response.raise_for_status()`

The `raise_for_status()` method is a convenient way to catch all 4xx and 5xx client and server errors. You can wrap the request in a `try...except` block to handle the `HTTPError` exception.

import requests

def fetch_url(url):
    try:
        response = requests.get(url)
        # Raise an exception for bad status codes (4xx or 5xx)
        response.raise_for_status()
        print(f"Successfully fetched {url}")
        return response.json()
    except requests.exceptions.HTTPError as http_err:
        print(f"HTTP error occurred: {http_err}")
        if http_err.response.status_code == 404:
            print("The resource could not be found.")
        elif http_err.response.status_code >= 500:
            print("The server is experiencing issues. Please try again later.")
    except requests.exceptions.RequestException as err:
        print(f"An error occurred: {err}")
    return None

# Example with a 404 error
fetch_url("https://httpbin.org/status/404")

# Example with a 500 error
fetch_url("https://httpbin.org/status/500")