python requests module status code

Python Requests Module Status Code

If you are working with web scraping or accessing HTTP requests in Python, then the requests module is a must-have tool. One of the most important parts of working with HTTP requests is dealing with the response status code.

The status code is a three-digit number that indicates the status of the requested resource. For example, a 200 status code indicates that the request was successful, whereas a 404 status code indicates that the requested page was not found.

Using Python Requests Module to Get Status Code

The requests module in Python makes it very easy to get the status code of an HTTP request. Here is an example:


import requests

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

print(status_code)

In this example, we are making a GET request to the website https://www.example.com and then storing the status code in the variable status_code. We can then print out the status code to see what it is.

Dealing with Different Status Codes

Knowing the status code is important because it allows you to handle different situations appropriately. For example, if you get a 404 status code, you may want to inform the user that the requested page was not found.

Here are some of the most common status codes:

  • 200: OK
  • 201: Created
  • 204: No Content
  • 301: Moved Permanently
  • 304: Not Modified
  • 400: Bad Request
  • 401: Unauthorized
  • 403: Forbidden
  • 404: Not Found
  • 500: Internal Server Error

You can use conditional statements to handle different status codes. Here is an example:


if status_code == 200:
  print('Success')
elif status_code == 404:
  print('Page not found')
else:
  print('Error')

In this example, we are checking if the status code is 200 or 404, and printing out a message accordingly. If the status code is neither 200 nor 404, then we print out a generic error message.

Conclusion

The requests module in Python makes it easy to get the status code of an HTTP request. Knowing the status code allows you to handle different situations appropriately and provide feedback to the user. Use conditional statements to handle different status codes and provide appropriate messages.