API Interface

The webcli.api module provides an interface for implementing API functions and APIs.

Usage example

Let’s start by defining one API function class.

class XFunction(APIFunction):
    # Default method will be get.
    __call__=APIFunction.get

    def _prepare(self,rq):
        rq.url += self.path
        if 'id' in rq.kwargs:
            rq.url += ('/%d' % rq.kwargs['id'])
            del rq.kwargs['id']

    def _prepare_post(self,rq):
        self._prepare(rq)
        rq.request.update(params=rq.kwargs)

    def _process(self,r):
        r.retry = False

Then we define the API with its functions.

class XAPI(API):
    def __init__(self,url,token):
        super().__init__(url)
        self._token=token
        self['/counters'] = XFunction()

    def _prepare(self,rq):
        rq.request.update(headers={'private-token': self._token})
        rq.url = self.url

    def _process(self,r):
        r.raise_for_status()
        r.data = r.json()

Instanciating the API and calling methods is then pretty straightforward.

api = XAPI('https://example.com/api','c11d5f2ddd2fc3fe')

# Get list of counters
result = api['/counters']()
result = api['/counters'].get()
# Get counter number 42
result = api['/counters'](id=42)
# Reset counter number 42 to 0
result = api['/counters'].post(id=42,value=0)

When calling an API function, the request goes through processing:

  • Request is processed by the API._prepare() method. API._prepare() is the default method if API._prepare_@method() is not defined.
  • Then, it is processed by the same method of the API function: APIFunction._prepare() by default if not APIFunction._prepare_@method()
  • Request is sent by the requests module.
  • The response is processed by the API._process() method. API._process() is the default method if API._process_@method() is not defined.
  • Then, the response is processed by the same method of the API function: APIFunction._process() by default if not APIFunction._process_@method()

This process is handled by the webcli.api.APIFunction.request() method.

API Functions

One API function is used to send a HTTP request.

API