Search code examples
jsonhttp-postwebapp2

webapp2 post request is not accepting json through POSTMAN


Here is my webapp2 code

class SendMessage(webapp.RequestHandler):
    def post(self):
        messageToId = self.request.POST.get("messageToId")
        message = self.request.POST.get("message")
        logging.info(messageToId)

When I hit above method in my html using

        var url = 'http://myapp.appspot.com/sendmessage';

        var messageToId = document.getElementById("messageToId").value;
        var message = document.getElementById("message").value;
        var jsonDta =  {
                messageToId : messageToId,
                message : message
            };
        $.post(url, jsonDta, function(data, status) {
        });

This is working fine.But when I try it with postman(selected post request -> raw data -> JSON/application) then it is not able to get json data and prints None in developer console. What is the issue ?


Solution

  • In your example you do not use a json payload in your post.
    It is a normal form post. To post json you have to JSON.stringify(jsonDta)

    If you send json, your handler looks like this:

    import json
    ....
    
    class SendMessage(webapp.RequestHandler):
    
        def post(self):
    
            json_string = self.request.body
            dict_object = json.loads(json_string)
    
            messageToId = dict_object['messageToId']
            message = dict_object.get('message', default='')
            logging.info(messageToId)