wiki:DeveloperGuidelines/WebServices

Version 6 (modified by Fran Boon, 13 years ago) ( diff )

--

DeveloperGuidelines

Web Services

We want to be able to access data from the database exported as JSON for easy use within Javascript clients.

This can be done by simply calling the RESTlike controller with the var ?format=json:

/sahana/module/resource?format=json           # Lists all records of this resource
/sahana/module/resource/id?format=json        # Display record with record.id==id
/sahana/module/resource/create?format=json    # ToDo
/sahana/module/resource/update/id?format=json # ToDo

The underlying functions are very easy within Web2Py since 1.55:

def display_json():
    "Designed to be called via AJAX to be processed within JS client."
    list=db(db.table.id==t2.id).select(db.table.ALL).json()
    response.view='plain.html'
    return dict(item=list)

Another approach (from T3: http://groups.google.com/group/web2py/browse_thread/thread/9ec8b06b158adb75): Model:

from gluon.storage import Storage
settings=Storage()
settings.rss_procedures=[]
settings.exposed_procedures=[]
settings.xmlrpc_procedures=[]
settings.json_procedures=[]
def rss(f):
    settings.rss_procedures.append(f.__name__)
    return f
def expose(f):
    settings.exposed_procedures.append(f.__name__)
    return f
def json(f):
    settings.json_procedures.append(f.__name__)
    return f
def xmlrpc(f):
    settings.xmlrpc_procedures.append(f.__name__) 

Controller:

def rss():
    if request.args and request.args[0] in settings.rss_procedures:
       feed=eval('%s(*request.args[1:],**dict
(request.vars))'%request.args[0])
    else:
       t2._error()
    import gluon.contrib.rss2 as rss2
    rss = rss2.RSS2(
       title=feed['title'],
       link = feed['link'],
       description = feed['description'],
       lastBuildDate = feed['created_on'],
       items = [
          rss2.RSSItem(
            title = entry['title'],
            link = entry['link'],
            description = entry['description'],
            pubDate = entry['created_on']) for entry in feed
['entries']]
       )
    response.headers['Content-Type']='application/rss+xml'
    return rss2.dumps(rss)

def run():
    if request.args and request.args[0] in
settings.exposed_procedures:
       return eval('%s(*request.args[1:],**dict
(request.vars))'%request.args[0])
    return 'Not Authorized'

def xmlrpc():
    methods=[eval(x) for x in settings.xmlrpc_procedures]
    return response.xmlrpc(request,methods)

def json():
    if request.args and request.args[0] in settings.json_procedures:
       import gluon.contrib.simplejson as sj
       return sj.dumps(eval('%s(*request.args[1:],**dict
(request.vars))'%request.args[0]))
    return 'Not Authorized' 

Another approach (using JSONRPC e.g. with Pyjamas):


DeveloperGuidelines DeveloperGuidelines

Note: See TracWiki for help on using the wiki.