When making HTTP requests in Python, you'll likely want to check the response code to see if the request succeeded. The urllib module provides easy ways to do this.
Let's explore how to access HTTP response codes using
Getting the Response Code
After making a request with
import urllib.request
response = urllib.request.urlopen("http://www.example.com")
print(response.getcode())
# 200
This prints the status code integer.
Response Code Categories
HTTP response codes are grouped into categories:
Knowing the category helps understand what happened, even if you don't know the specific code.
Handling Different Response Codes
You can handle different code categories in your program flow:
if response.getcode() >= 200 and response.getcode() < 300:
print("Success!")
elif response.getcode() >= 300 and response.getcode() < 400:
print("Redirect detected")
else:
print("An error occurred")
This prints a message based on the code.
Retrieving the Reason Phrase
In addition to the numeric code, the response contains a text reason phrase explaining it:
print(response.reason)
# OK
The phrase gives more context about the result.
Conclusion
Knowing how to check HTTP response codes allows detecting errors or other outcomes when making web requests with Python. The