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')
print(response.status_code)
# 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:

    try:
      response = requests.get(url)
      response.raise_for_status()
    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:

    The easiest way to do Web Scraping

    Get HTML from any page with a simple API call. We handle proxy rotation, browser identities, automatic retries, CAPTCHAs, JavaScript rendering, etc automatically for you


    Try ProxiesAPI for free

    curl "http://api.proxiesapi.com/?key=API_KEY&url=https://example.com"

    <!doctype html>
    <html>
    <head>
        <title>Example Domain</title>
        <meta charset="utf-8" />
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
    ...

    X

    Don't leave just yet!

    Enter your email below to claim your free API key: