Demystifying HTTP Status Codes in Python Requests

Feb 1, 2024 ยท 2 min read

When working with the Python Requests library to make HTTP requests, you'll invariably encounter HTTP status codes in the response. Codes like 200, 404 and 500 that give you information on how the request went.

But what do these numeric codes actually mean? Thankfully, Requests makes it easy to get a human-readable description for any status code.

Getting a Status Code Description

The Response object in Requests contains a handy built-in method called .reason that returns a text description of the status code:

import requests

response = requests.get('https://api.example.com/items/1')
print(response.status_code) # 200 
print(response.reason) # OK

So for a 200 OK response, this would print out:

200
OK

Nice and easy!

Custom Descriptions

Sometimes you may want to provide a custom description for a certain status code instead of the default text.

You can pass this custom reason when creating the Response object:

from requests import Response

response = Response() 
response.status_code = 200
response.reason = 'Everything is awesome!'

print(response.reason) # Everything is awesome!

Handling Errors

Checking the status code reason is especially handy when handling errors. You can print the reason in exception handling to better understand what went wrong:

try:
  response = requests.get('https://api.example.com/invalid-endpoint')
except requests.exceptions.RequestException as err:
  print(err.response.status_code, err.response.reason) # 404 Not Found

So next time you get a cryptic status code, remember to check the .reason attribute for a helpful description!

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: