Search code examples
pythonjsontornado

Tornado application/json support


Does Tornado support Content-Type "application/json"?

According to the call stack (assuming stream_request_body = False), the only method called to parse the request body is parse_body_arguments (httputil.py 662), which only accepts "application/x-www-form-urlencoded" and "multipart/form-data"


Solution

  • The solution is pretty trivial. You just have to json.loads() the received body and trust that it's a proper JSON-encoded dictionary (if you want, catch the exception and provide meaningful feedback). You can't expect application/json to be in the Content-Type; during a POST that'll already be application/x-www-form-urlencoded.

    Here is a sample server:

    import json
    import tornado.httpserver
    import tornado.ioloop
    import tornado.web
    
    class MyHandler(tornado.web.RequestHandler):
        def post(self):
            data = json.loads(self.request.body.decode('utf-8'))
            print('Got JSON data:', data)
            self.write({ 'got' : 'your data' })
    
    if __name__ == '__main__':
        app = tornado.web.Application([ tornado.web.url(r'/', MyHandler) ])
        http_server = tornado.httpserver.HTTPServer(app)
        http_server.listen(8888)
        print('Starting server on port 8888')
        tornado.ioloop.IOLoop.instance().start()
    

    You can test this using e.g. curl:

    curl -H 'Content-Type: application/json' -d '{"hello": "world"}' http://localhost:8888/