Restful-flask Parsing Json Arrays With Parse_args()
This's my code: parser = reqparse.RequestParser(bundle_errors=True) parser.add_argument('list', type=list, location='json') class Example(Resource): def post(self):
Solution 1:
chuong nguyen is right in his comment to your question. With an example:
defpost(self):
parser = reqparse.RequestParser()
parser.add_argument('options', action='append')
parser = parser.parse_args()
options = parser['options']
response = {'options': options}
return jsonify(response)
With this, if you request:
curl -H 'Content-type: application/json' -X POST -d '{"options": ["option_1", "option_2"]}' http://127.0.0.1:8080/my-endpoint
The response would be:
{"options":["option_1","option_2"]}
Solution 2:
Here is a workaround a came up with. But it really seems like a big hack to me...
By extending the input types you can create your own "array type" like that:
from flask import request
defarrayType(value, name):
full_json_data = request.get_json()
my_list = full_json_data[name]
if(notisinstance(my_list, (list))):
raise ValueError("The parameter " + name + " is not a valid array")
return my_list
and than use it with the parser:
parser = reqparse.RequestParser(bundle_errors=True)
parser.add_argument('list', type=arrayType, location="json")
It works, but I think there should be a proper way to do this within flaks-restful. I imagine calling request.get_json()
for each JSON array is also not the best in terms of performance, especially if the request data is rather big.
Post a Comment for "Restful-flask Parsing Json Arrays With Parse_args()"