HTTP GET Request with Error Handling Using urllib3

  • Share this:

Code introduction


This function uses urllib3's PoolManager to make an HTTP GET request and returns the response data. If the request fails, it returns an error message.


Technology Stack : urllib3, HTTP GET request

Code Type : Function

Code Difficulty : Intermediate


                
                    
def fetch_random_resource(url, headers=None, timeout=5):
    from urllib3 import PoolManager, HTTPError

    try:
        with PoolManager(headers=headers) as http:
            response = http.request('GET', url, timeout=timeout)
            return response.data
    except HTTPError as e:
        return f"HTTP error occurred: {e}"
    except Exception as e:
        return f"An error occurred: {e}"