Search code examples
pythonjsonflaskflask-restful

How to check for empty JSON field in flask reqparse for a post request?


I need to check for empty string in JSON field for a post request in flask using reqparse. Can I achieve it with flask reqparse module?

I have tried :

self.parser.add_argument('name', 
                 type=str, 
                 required=True, 
                 trim=True, 
                 location='json'
                )
self.parser.parse_args()

It is checking if the name field in {"name":"xyz"} is present, However I also want to check for empty values {"name":""} , so that I can throw error to user that name can not be empty. Is it possible to do that using reqparse ?


Solution

  • From looking at the reqparse documentation and how to check for empty strings in python You could do something like...

    args = self.parser.parse_args()
    name = args['name']
    if not name:
        # do your foo here if name is not truthy
    

    Since args['name'] can return an array, I'd be careful about the following edge cases.

    [] == false
    ['foo'] == true
    [' ', '   '] == true
    

    So it might be better do something along the lines of

    args = self.parser.parse_args()
    names = args['name']
    for name in names:
        if not name:
            # if not truthy