python requests module get status code

Python Requests Module: Get Status Code

As someone who works with APIs frequently, I have found the need to quickly and easily retrieve the status code of a response. The requests module in Python makes this process incredibly simple.

To begin, you will need to have the requests module installed. You can install it by running the following command:


      pip install requests
    

Once you have requests installed, you can make a request to an API endpoint using the get() method:


      import requests
      
      response = requests.get('https://example.com/api')
    

The response object that is returned by the get() method contains a status_code attribute. You can access this attribute to retrieve the status code of the response:


      status_code = response.status_code
    

The status code will be an integer, such as 200 for a successful response or 404 for a not found error.

Alternative Method

Another way to retrieve the status code is by accessing the ok attribute. This attribute will return True if the status code is less than 400, indicating a successful response:


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