Search code examples
pythonrestpostgettornado

Sending Post,Get Requests manually to RequestHandler


I am trying to make a request handler for making a REST Api using Tornado. But I cant seem to find a way to send the request and/or catch the request properly with Tornado.

My Code is:

class VersionHandler2(tornado.web.RequestHandler):
    def post(self,*args,**kwargs):
        print "post"
        print kwargs
        print args
        response = { 'version': '3.5.1'}
        x = self.get_argument('query')
        self.write(kwargs)
    def get(self, *args, **kwargs):
        print "GET"
        response = { 'GET': '3.5.1'}
        self.write(response)

if __name__ == '__main__':
    sx = Server(7231,[ (r"/prost/", VersionHandler2),(r"/about/", VersionHandler)])

    sx.startServer()

The Get method is working sending the response but the post method is not able to get the post data. I have tried using Advanced Rest Client and SENSE , but got no luck. I am trying to send the data as JSON, and have used the proper prfrences and its sending it as json.

My request body as shown in ARC is

Localhost: 7231/ Content-Type: application/json Content-Length: 39 Source message

POST /prost/ HTTP/1.1
 HOST: localhost:7231
 localhost: 7231/
 content-type: application/json
 content-length: 39

 {
 "query": [
 "paul"
 ]
 }

Also, is it possible to send JSON queries using GET Method? I am trying to build something like elastic search and want to use the 4 CRUD Methods -> Post,Put,Get,Delete and send JSON data as query to each method.


Solution

  • The POST request body is in self.request.body.

    If the POST request is from an HTML form, then self.get_argument(name) returns a named field of the HTML form. But if you have an API client sending JSON to your server, instead of sending form-encoded data, then you should just use something like json.loads(self.request.body).