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
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