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:

    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: