How do I check the status code of a response in Requests?

In Python, the requests library is commonly used for making HTTP requests. You can check the status code of a response you receive from making a request using the status_code property of the Response object. Below is an example of how to do this:

import requests

# Make a GET request to the specified URL
response = requests.get('https://httpbin.org/get')

# Check the status code of the response
status_code = response.status_code

print(f"Status Code: {status_code}")

# You can also use the response object in a conditional expression
if response.ok:
    print("The request was successful!")
else:
    print("The request failed!")

The status_code property will give you the HTTP status code as an integer. Common status codes include:

  • 200: OK
  • 301: Moved Permanently
  • 400: Bad Request
  • 401: Unauthorized
  • 403: Forbidden
  • 404: Not Found
  • 500: Internal Server Error

The Response object also has a reason property that gives you the text representation of the status code, which can sometimes be more informative. You can access it like this:

print(f"Status Code: {response.status_code} - Reason: {response.reason}")

Additionally, the requests library provides a built-in status code lookup object called codes that can be used to make your code more readable:

if response.status_code == requests.codes.ok:
    print("The request was successful!")
else:
    print("The request failed with status code:", response.status_code)

Remember that the requests library will not raise an exception for most HTTP error status codes (such as 404 or 500). If you want to ensure an exception is raised for such cases, you can call the raise_for_status() method on the Response object:

try:
    response = requests.get('https://httpbin.org/status/404')
    response.raise_for_status()
except requests.exceptions.HTTPError as err:
    print(f"HTTP error occurred: {err}")

When raise_for_status() is called, it will raise an HTTPError if the HTTP request returned an unsuccessful status code. If the status code is between 200 and 400, it will return None and proceed without an error.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon