Search code examples
pythonjsonrestflaskflask-restful

Parsing a list of integers in flask-restful


I'm using the flask-restful, and I'm having trouble constructing a RequestParser that will validate a list of only integers. Assuming an expected JSON resource format of the form:

{
    'integer_list': [1,3,12,5,22,11, ...] # with a dynamic length
}

... and one would then create a RequestParser using a form something like:

from flask.ext.restful import reqparse
parser = reqparse.RequestParser()
parser.add_argument('integer_list', type=list, location='json')

... but how can i validate is an integer list?


Solution

  • You can check types with isinstance, here you set the type to int (integer).

    This would work like this:

    a=1    
    isinstance(a,int)
    

    evaluates to TRUE

    To check this for a whole list use all(). and loop through the list with the for loop so every element of the list gets checked.

    if all(isinstance(x,int) for x in integer_list):
        parser.add_argument('integer_list', type=list, location='json')
    

    In your case this should evaluate to TRUE if all elements are integers and executes the code in the for loop