Hands-On Guide to Python Requests Status Codes

Nov 17, 2023 ยท 2 min read

Status codes are a vital part of working with the Python Requests library. When you make a request, the response contains a status code conveying the outcome. Handling statuses properly is crucial for writing robust scripts and applications.

In this hands-on guide, you'll learn how to access, interpret, and handle status codes in Python Requests.

Accessing Status Codes

To view the status code of a response, use the status_code attribute:

response = requests.get('<https://api.example.com>')
print(response.status_code) # 200

The reason attribute provides the textual description:

print(response.reason) # OK

Common Status Codes

Some status codes you'll frequently encounter are:

  • 200 OK - Request succeeded
  • 301 Moved Permanently - Resource relocated permanently
  • 400 Bad Request - Malformed request
  • 403 Forbidden - No access to resource
  • 404 Not Found - Resource does not exist
  • 500 Internal Server Error - Server error
  • Status Workflows

  • For 2xx, the request succeeded. Extract data, print messages, etc.
  • Inspect 3xx codes to follow redirects as needed.
  • Handle 4xx by debugging request issues on the client side.
  • Retry 5xx codes carefully as the server had an error.
  • Automated Handling

  • Use raise_for_status() to get exceptions on bad statuses.
  • Build custom decorators to centralize error handling.
  • Proper status code handling will make your Python request scripts far more resilient. Leverage the techniques here to write production-ready code!

    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: