Ryan Martin
Ryan Martin

Reputation: 1693

How do I properly serve json data with Python?

I've searched high and low for an answer and can't figure out what i'm doing wrong. I'm creating an api that returns json data. I would prefer the response to be printed to the browser as well, if possible. What am I doing wrong?

#!/usr/bin/python

import simplejson as json

class serve_json:
    def __init__(self):
        x = {"msg": "Some message", "error": "Some error"}

        html_to_display = 'Content-Type: application/json\n\n'
        html_to_display += json.dumps(x)
        print html_to_display

serve_json()

The above code doesn't work, and it doesn't print the result to the browser. If I change the Content-Type to "text/html", it prints to the screen fine, but still doesn't work as json data.

Upvotes: 1

Views: 2772

Answers (1)

Zach Kelling
Zach Kelling

Reputation: 53859

I'd recommend bottle, it's really easy to build simple little JSON services with it:

from bottle import *

@get('/')
def serve_json():
    return {"msg": "Some message", "error": "Some error"}

run(host='localhost', port=8080)

One neat feature of bottle is that it'll automatically serve JSON from a route that returns a dict. You can execute python serve_json.py to run your app using the built-in HTTP server, host it as a WSGI application, etc.

Upvotes: 3

Related Questions