How to retrieve the status code of an HTTP response in Python?

Published on Aug. 22, 2023, 12:17 p.m.

To retrieve the status code of an HTTP response in Python, you can use the status_code attribute of the response object returned by the requests library. Here’s an example:

import requests

response = requests.get('https://www.google.com')
status_code = response.status_code

if status_code == 200:
    print('The request was successful!')
else:
    print(f'The request failed with status code {status_code}')

In this example, we send a GET request to https://www.google.com and store the response object in the response variable. The status code of the response is then retrieved using the status_code attribute, and we use it to determine whether the request was successful or not.

The status_code attribute returns an integer representing the status code of the response, such as 200 for a successful request or 404 for a resource not found error. More information about the different status codes can be found in the HTTP/1.1 specification, RFC 7231.