Bottle and Json

arinte picture arinte · Aug 17, 2010 · Viewed 18.4k times · Source

How do I go about returning json data from a bottle request handler. I see a dict2json method in the bottle src but I am not sure how to use it.

What is in the documentation:

@route('/spam')
def spam():
    return {'status':'online', 'servertime':time.time()}

Gives me this when I bring up the page:

<html>
    <head></head>
    <body>statusservertime</body>
</html>

Answer

Andrew picture Andrew · Aug 17, 2010

Simply return a dict. Bottle handles the conversion to JSON for you.

Even dictionaries are allowed. They are converted to json and returned with Content-Type header set to application/json. To disable this feature (and pass dicts to your middleware) you can set bottle.default_app().autojson to False.

@route('/api/status')
def api_status():
    return {'status':'online', 'servertime':time.time()}

Taken from the documentation.

http://bottlepy.org/docs/stable/api.html#the-bottle-class