vendredi 18 août 2017

Design API wrapper with "God object"

Here's the problem:

There's a rather large web API and I'm trying to write wrapper for it. All examples of API wrappers I found have same design - single module with large class, something like this:

class API(object):
    def __init__(self, api_key):
        self._api_key  = api_key
        self._base_url = 'https://api.baseurl.com'

    def _request(self, url):
        pass

    def api_method1(self, params):
        pass

    def api_method2(self, params):
        pass

    ...

This is a proper design for a small API. For large APIs I think it's better to separate all methods into different groups (modules), for example:

|- api
|  |-- __init__.py
|  |-- request.py
|  |-- user.py
|  |-- test.py
|  |-- support.py
|  |-- status.py
|    ...
|- requirements.txt
|- setup.py
|- LICENSE.txt
|- README.md

However I still need an API class to store global variables between modules like api_key, base_url and so on. Also I need to link all methods to this class, so I can easily access them:

api = API('api_key')
api.test()
api.method1()
api.method2()
...

How can I link all module methods to API class?

Aucun commentaire:

Enregistrer un commentaire