dkakoti
dkakoti

Reputation: 667

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 ?

Upvotes: 2

Views: 5531

Answers (2)

Prakash Takkalaki
Prakash Takkalaki

Reputation: 21

def non_empty_string(s):
if not s:
    raise ValueError("Must not be empty string")
return s
parser.add_argument('name', required=True, nullable=False, type=non_empty_string)

i referred this from following link

Upvotes: 0

Skam
Skam

Reputation: 7798

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 

Upvotes: 2

Related Questions