API Navigator Logo

Python Requests Status Code Handling

Author: Newtum

This example demonstrates how to check and handle different HTTP status codes returned by an API using the Python Requests library.

Checking the Status Code

The `response` object has a `status_code` attribute that contains the integer status code of the response. You can use conditional logic to handle different outcomes.

import requests

def check_status(url):
    response = requests.get(url)
    print(f"\nRequest to {url}")
    if response.status_code == 200:
        print("Success! (200 OK)")
    elif response.status_code == 404:
        print("Error: Resource not found (404 Not Found)")
    elif response.status_code >= 500:
        print(f"Error: Server error ({response.status_code})")
    else:
        print(f"Received status code: {response.status_code}")

check_status('https://httpbin.org/status/200')
check_status('https://httpbin.org/status/404')
check_status('https://httpbin.org/status/503')

Raising an Exception for Bad Statuses

You can use `response.raise_for_status()` to automatically raise an `HTTPError` if the request returned an unsuccessful status code (4xx or 5xx).

import requests

try:
    response = requests.get('https://httpbin.org/status/404')
    # This will raise an HTTPError for the 404 status
    response.raise_for_status()
except requests.exceptions.HTTPError as err:
    print(f"HTTP Error Occurred: {err}")