Gary Ng
Gary Ng

Reputation: 443

Flask-Restful: can't parse args of json nested value

I've got the json

{
    "message":  {
        "foo": "foo",
        "bar": "bar"
    }
}

And parser:

parser = reqparse.RequestParser(bundle_errors=True)
parser.add_argument('foo', type=str, required=True)
parser.add_argument('bar', type=str, required=True)
args = parser.parse_args()

And the error is : {'foo': 'Missing required parameter in the JSON body or the post body or the query string', 'bar': 'Missing required parameter in the JSON body or the post body or the query string'}

Upvotes: 0

Views: 3674

Answers (1)

Sreenadh T C
Sreenadh T C

Reputation: 611

Since your 'foo' and 'bar' keys are inside 'message', the JSON parsing has to start from 'message'. ie. You have to let know the parser about 'message' before you can parse 'foo' from it.

For this, you have to set up a root parser which parses your 'message'. You can do this in the following way:

root_parser = reqparse.RequestParser()
root_parser.add_argument('message', type=dict)
root_args = root_parser.parse_args()

message_parser = reqparse.RequestParser()
message_parser.add_argument('foo', type=dict, location=('message',))
message_parser = message_parser.parse_args(req=root_args)

For more info please take a look at the issue from github

Upvotes: 2

Related Questions