Search code examples
pythonflaskflask-restplus

Adding multiple json fields in flask_restplus RequestParser


I want to expect a request where the request.json looks like:

{
  "app_name": "app",
  "model_name": "model"
}

I created the following parser:

parser = reqparse.RequestParser()
parser.add_argument('app_name', location='json', required=True)
parser.add_argument('model_name',  location='json', required=True)

And am using the parser as:

class ModelList(Resource):
    @api.expect(parser)
    def get(self):
    """Get all matching model records"""
    ....

This shows up in the service as:

enter image description here

But when I try this out, my request is translated as following:

enter image description here

I expect the request to look like:

curl -X GET "http://localhost:5000/model" -H  "accept: application/json" -H  "Content-Type: application/json" -d '{"app_name": "test","model_name": "affinity"}'

and not:

curl -X GET "http://localhost:5000/model" -H  "accept: application/json" -H  "Content-Type: application/json" -d "affinity"

What am I doing wrong?


Solution

  • TypeError: HEAD or GET Request cannot have a body.

    Refer to this SO question for why it cannot (should not) have one: HTTP GET with request body

    To fix, either remove location='json' or specify location='args' instead.

    parser = reqparse.RequestParser()
    parser.add_argument('app_name', required=True)
    parser.add_argument('model_name', required=True)
    
    parser = reqparse.RequestParser()
    parser.add_argument('app_name', location='args', required=True)
    parser.add_argument('model_name', location='args', required=True)
    

    Both will let Swagger know to send the arguments in query string and the parser know to look there.