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:

    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!