When making HTTP requests in Python, you'll often want to check the status code of the response to determine if the request succeeded or not. The requests library makes this easy.
Here's a quick example:
import requests
response = requests.get('https://www.example.com')
print(response.status_code)
This will print the status code integer for the response. Some common codes you may see:
You can check for specific codes like this:
if response.status_code == 200:
print('Success!')
elif response.status_code == 404:
print('Not Found.')
Or simply check if it's a successful code:
if response.status_code >= 200 and response.status_code < 300:
print('Success!')
If the status is 400 or 500, you may want to handle it differently or log the error.
One tip is to import Python's
import requests, http.client
print(http.client.responses[response.status_code])
This prints a text description of each code.
Handling status codes correctly ensures your Python scripts detect issues, retry requests, and even notify you if things fail. Sites often use codes like 429 for rate limiting, so you'll want to catch that.
Overall, carefully checking status codes saves future headaches! Requests makes it simple.