I'm trying to build a wrapper for an API. The API can send me all kind of response: 200, 403, 404, 429, 500
now I want my wrapper to be able to handle exceptions, this is my current class:
class API:
def __init__(self, key):
self.key = key
def get_some_object_from_a_endpoint(self):
call = requests.get("adress_of_a_endpoint&api_key={0}".format(self.key))
content = call.json()
my_object = MyClass.build_object_from_api_data(content)
return my_object
Now I thought about defining a function in my class that will manage all the call and call this function in each of my endpoint, so my class will look like this:
class API:
def __init__(self, key):
self.key = key
@staticmethod
def check_exception(request):
if request.status_code == 200:
return request.json()
if request.status_code == 404:
print("Not found")
... # management of other exceptions
def get_some_object_from_a_endpoint(self):
call = requests.get("adress_of_a_endpoint&api_key={0}".format(self.key))
request_result = self.check_exception(call)
if request_result:
content = call.json()
my_object = MyClass.build_object_from_api_data(request_result)
return my_object
else:
return MyClass()
I will use my API wrapper that way:
api = API("my_key")
my_object = api.get_some_object_from_a_endpoint() # Will have the data from the API, the default object or raised some exception depending of the error code
What annoy me with my solution is that for every endpoint I will have the same piece of code:
call = requests.get("adress_of_a_endpoint&api_key={0}".format(self.key))
request_result = self.check_exception(call)
if request_result:
...
return my_object
else:
return MyClass()
Does my solution respect common design pattern? Is there a better practices for solving this kind of problem?
Aucun commentaire:
Enregistrer un commentaire