Kiss a rest api
Home Home Contact us Contact
home News Projects Tests Files Follow manatlan on Twitter Sign in
back 2017/01/13 14:53

Kiss a rest api

I see a lot of things about python libs to help to make restful api, nowadays. Sure, hug is beautiful.

Last year, I've made my own lib for that. But since some months, I use this KISS way, and I'm really happy with it :

Server side, I create a HTTP POST endpoint (here with bottle):

@post("/server")
def serverEndpoint():
    try:
        datas=json.loads(request.body.read())
        c=lambda d: globals()["API_"+ d.keys()[0] ]( **d[ d.keys()[0] ] )
        return {"result":[c(i) for i in datas] if type(datas)==list else c(datas)}
    except Exception as e:
        import traceback
        return {"error":traceback.format_exc()}

Now, I can create a lot of serverside API (method which starts with 'API_'), example:

def API_add(a,b=1):
    return a+b

And client side, I call them easily, like this (here with angularjs, but likely the same with JS's fetch) :

$http.post("/server", {add: {a:12, b:42} } ).then( ... )

And better, within 1 http request, I can call multiple api too, like this :

$http.post("/server", [ {add:{a:36,b:29}} , {add:{a:27}} ] ).then( ... )

If I call one method, the result is in the "result" attribut of the response. If I call multiple, results are in a list in the "result" attribut of the response. If server side error, the traceback is in the "error" attribut of the response.

It's very useful in a lot of cases, and it's hard to make simpler !?

RSS Python Powered Get Ubuntu
©opyleft 2008-2019 - manatlan