python requests check status code

hljs.highlightAll();

Python Requests Check Status Code

If you are working with Python requests, you might want to check the status code of the HTTP response. The status code tells you whether the request was successful or not.

Method 1: Using the status_code attribute

You can use the status_code attribute of the response object to get the status code:


import requests

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

Method 2: Using exceptions

You can also use exceptions to handle specific status codes. For example, if you expect a 404 error, you can handle it like this:


import requests

try:
    response = requests.get('https://www.example.com/404')
    response.raise_for_status()
except requests.exceptions.HTTPError as error:
    print(error)
	

Method 3: Using the ok attribute

The ok attribute of the response object tells you if the request was successful:


import requests

response = requests.get('https://www.example.com')
if response.ok:
    print('Request successful!')
else:
    print('Request failed!')
	

Conclusion

There are multiple ways to check the status code of a Python requests response. You can use the status_code attribute, exceptions, or the ok attribute. Choose the method that fits your needs best!