Handling HTTP Response Codes with Python's urllib

Feb 8, 2024 ยท 2 min read

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 urllib.

Getting the Response Code

After making a request with urllib.request, you can access the response code through the getcode() method on the response:

import urllib.request

response = urllib.request.urlopen("http://www.example.com")
print(response.getcode())
# 200

This prints the status code integer. 200 means the request succeeded.

Response Code Categories

HTTP response codes are grouped into categories:

  • 2xx means success
  • 3xx means a redirect
  • 4xx means a client-side error
  • 5xx means a server-side error
  • 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 getcode() and reason attributes on urllib responses make this easy. Give the code a try in your programs!

    Browse by tags:

    Browse by language:

    Tired of getting blocked while scraping the web?

    ProxiesAPI handles headless browsers and rotates proxies for you.
    Get access to 1,000 free API credits, no credit card required!