Parsing a list of integers in flask-restful
You can use action='append'. For example:
parser.add_argument('integer_list', type=int, action='append')
Pass multiple integer parameters:
curl http://api.example.com -d "integer_list=1" -d "integer_list=2" -d "integer_list=3"
And you will get a list of integers:
args = parser.parse_args()
args['integer_list'] # [1, 2, 3]
An invalid request will automatically get a 400 Bad Request response.
You cannot in fact. Since you can pass a list with multiple kinds of types, e.g. [1, 2, 'a', 'b']
, with reqparser, you can only parse with type=list
.
You need to check the elements of the list one by one by yourself. The code looks like below:
parse_result = parser.add_argument('integer_list', type=list, location='json')
your_list = parse_result.get('integer_list', [])
for element in your_list:
if isinstance(element, int):
# do something
print "element is int"
else:
# do something else
print "element is not int"