Sunday 29 January 2012

Python simpleapi flask

I was looking for a quick and simple way to implement APIs with Flask and came across one aptly called Simpleapi.

After going through the examples, there seems to be a problem with getting POST data to the server, so after a small edit, GET works fine.

By default simpleapi client sends POST data, we will need to make a small change to make it send GET data. In /lib/python2.7/site-packages/simpleapi/client/client.py, line 62, change

client.py
try:
                response = urllib.urlopen(self.ns,
                                        urllib.urlencode(data))
Change to:
try:
                response = urllib.urlopen(self.ns %
                                        urllib.urlencode(data))
Flask server
from flask import Flask

from simpleapi import Route
from handler import calculator

app = Flask(__name__)
app.route('/api/', methods=['GET'])(Route(calculator, framework='flask', debug=True))

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8888, debug=True)
Client
#!/usr/bin/env python

from simpleapi import Client, RemoteException

calculator = Client(ns='http://127.0.0.1:8888/api/?%s')
print "the answer is", calculator.add(a=23, b=3)

1 comment: