Handling HTTP Status Codes with Python Requests

Feb 3, 2024 ยท 2 min read

When making HTTP requests in Python, you'll often want to check the status code of the response to determine if the request succeeded or not. The requests library makes this easy.

Here's a quick example:

import requests

response = requests.get('https://www.example.com')
print(response.status_code)

This will print the status code integer for the response. Some common codes you may see:

  • 200 - Success
  • 301, 302 - Redirects
  • 400 - Client error like a bad request
  • 500 - Server error
  • You can check for specific codes like this:

    if response.status_code == 200:
        print('Success!')
    elif response.status_code == 404:
        print('Not Found.')

    Or simply check if it's a successful code:

    if response.status_code >= 200 and response.status_code < 300:
        print('Success!')

    If the status is 400 or 500, you may want to handle it differently or log the error.

    One tip is to import Python's http module which contains dictionaries for status code meanings:

    import requests, http.client
    
    print(http.client.responses[response.status_code])

    This prints a text description of each code.

    Handling status codes correctly ensures your Python scripts detect issues, retry requests, and even notify you if things fail. Sites often use codes like 429 for rate limiting, so you'll want to catch that.

    Overall, carefully checking status codes saves future headaches! Requests makes it simple.

    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!