diff --git a/README.md b/README.md index 4223b9b..5f96914 100644 --- a/README.md +++ b/README.md @@ -22,3 +22,7 @@ The ApiWrapper class defines custom exceptions for handling API request and resp - `InvalidApiResponse` is raised when the API response is not a valid JSON. You can catch these exceptions and handle them accordingly in your code. + +## Debugging +To turn on debugging, initialize the wrapper with `debug=True`. This will set the log level of +`urllib3` to `logging.DEBUG` \ No newline at end of file diff --git a/src/main.py b/src/main.py index 537c0df..2dbace5 100644 --- a/src/main.py +++ b/src/main.py @@ -1,4 +1,4 @@ -from wrapper import ApiWrapper +import wrapper def main(): @@ -6,24 +6,16 @@ def main(): ApiWrapper example. """ # Initialize ApiWrapper - api = ApiWrapper('https://jsonplaceholder.typicode.com') + api = wrapper.ApiWrapper('https://jsonplaceholder.typicode.com', debug=True) # Test get_users method - users = api.get_users() - for user in users: - print(user) - - # Reinitialize ApiWrapper with broken proxy - # This should raise an InvalidRequestException - api = ApiWrapper( - 'https://jsonplaceholder.typicode.com', - proxies={'http': 'http://localhost:23451', 'https': 'http://localhost:23451'} - ) - - # Test broken proxy - users = api.get_users() - for user in users: - print(user) + try: + users = api.get_users() + except wrapper.ApiRequestException as e: + print(str(e)) + else: + for user in users: + print(user) if __name__ == '__main__': diff --git a/src/wrapper.py b/src/wrapper.py index 5245492..565ecc8 100644 --- a/src/wrapper.py +++ b/src/wrapper.py @@ -6,11 +6,15 @@ endpoints of the API using HTTP requests. It supports custom headers and proxies additional flexibility. """ import json +import logging import requests from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry +logger = logging.getLogger() + + class InvalidApiResponse(Exception): pass @@ -31,13 +35,14 @@ class ApiWrapper: base_url (str): The base URL of the API. headers (dict, optional): Dictionary containing customer headers to be sent with each request. proxies (dict, optional): Dictionary containing proxy settings to be used for requests. + debug (bool, optional): Setting this to true will print `urllib3` debug information. Attributes: base_url (str): The base URL of the API. session (requests.Session): Persistent HTTP session. """ - def __init__(self, base_url, headers=None, proxies=None): + def __init__(self, base_url, headers=None, proxies=None, debug=False): self.base_url = base_url self.session = requests.Session() @@ -50,6 +55,13 @@ class ApiWrapper: if proxies: self.session.proxies.update(proxies) + if debug: + if not logger.handlers: + logging.basicConfig() + + logging.getLogger("urllib3").setLevel(logging.DEBUG) + + def __get(self, endpoint, params=None): url = self.base_url + endpoint