python requests module check status code

Checking Status Code with Python Requests Module

If you're working with APIs or scraping web pages, you'll often need to check the response status code to make sure that your request was successful. In Python, the Requests module makes this easy.

Method 1: Using the status_code attribute

The simplest way to check the status code of a request is to use the status_code attribute of the response object returned by the requests.get() method. Here's an example:


import requests

response = requests.get('https://www.example.com')
if response.status_code == 200:
    print('Request was successful!')
else:
    print('Request failed with status code:', response.status_code)
  

Method 2: Raising exceptions with raise_for_status()

The Requests module also provides a built-in method called raise_for_status(), which raises an HTTPError if the request was unsuccessful (i.e. any status code other than 2xx). Here's an example:


import requests

response = requests.get('https://www.example.com')
try:
    response.raise_for_status()
    print('Request was successful!')
except requests.exceptions.HTTPError as e:
    print('Request failed with error:', e)
  

Method 3: Using a custom function

If you're performing a lot of requests and want to reuse the status code checking logic, you can create a custom function that encapsulates the logic. Here's an example:


import requests

def check_response(response):
    if response.status_code == 200:
        print('Request was successful!')
    else:
        print('Request failed with status code:', response.status_code)

response1 = requests.get('https://www.example.com')
check_response(response1)

response2 = requests.get('https://www.example.com/404')
check_response(response2)