Handling HTTP Status Codes Gracefully with Python Requests

Feb 3, 2024 ยท 2 min read

The Python Requests library makes it easy to interact with web APIs and services. A key aspect of working with APIs is properly handling HTTP status codes in your Python code. Requests provides convenient ways to check status codes and take appropriate actions.

When you make a request with Requests, the Response object contains a status_code attribute that holds the numeric HTTP status code returned by the server. For example:

import requests

response = requests.get('https://api.example.com/users')
# 200

While you could directly compare the status code to numeric values like 200, 401 etc., Requests provides more readable attributes that evaluate to True or False:

if response.ok:
  # Status code 200-299
if response.status_code == requests.codes.NOT_FOUND:
  # Handle 404 error

This makes status code handling easy to read and maintain. Some common status code checks:

  • response.ok - True for 200-299 status codes
  • response.status_code == requests.codes.NOT_FOUND - 404 error
  • response.status_code == requests.codes.FORBIDDEN - 403 error
  • response.status_code == requests.codes.BAD_REQUEST - 400 error
  • For web APIs, 4xx client errors and 5xx server errors are common. When an error occurs, you need to handle it appropriately in your code instead of letting the script crash:

      response = requests.get(url)
    except requests.exceptions.HTTPError as err:
      # Log error details
      print(f"HTTP Error: {err}")  
    except requests.exceptions.ConnectionError:
      # Network error
      print("Network error occurred")  

    Carefully handling status codes is important for writing robust Python code that interacts with web services. Requests makes status code checking concise and clean.

    Browse by tags:

    Browse by language:

    Tired of getting blocked while scraping the web?

    ProxiesAPI handles headless browsers and rotates proxies for you.
    Get access to 1,000 free API credits, no credit card required!