Search code examples
pythonflaskflask-restplus

Flask rest plus Parser does not seem to work with post


I have written below code endpoint to post data received from front end, I have implemented the same way for get and it works but does not work for post

parser = reqparse.RequestParser()
parser.add_argument("update", type=bool, help="Update the data set") 
parser.add_argument(
"set_name", type=str, help="Name of the set you want to add

@api.route("/add_set")
 class AddNewSet(Resource): 
@api.doc(parser=parser) 
def post(self):
     """ endpoint that handles request for deploying services 
         :return: (int) deployed service id from database. 
     """

          print "Hello hellooo"
          args = parser.parse_args() 
          print "doink"

throws error:

{ "message": "Failed to decode JSON object: No JSON object could be decoded" }

And the text "doink" does not get printed so I gave doubt parser.parse_args() is not working as expected I believe or I am doing something wrong.


Solution

  • By default, the RequestParser looks for args from request.json and request.values

    Plz see: https://flask-restplus.readthedocs.io/en/stable/parsing.html#argument-locations

    As for your code, I haven't try your way to define args for post, I do this way

    @api.expect(api.model(
      'ModelName', dict(
        arg1 = fields.String(required=True),
        arg2 = fields.Integer,
      )
    ))
    def post(self):
      return {'result': 'success'}
    

    I also recommend to give a clear return clause, even return None.