PythonUser PythonUser - 1 month ago 8
JSON Question

python-RequestParser is not returning error when different datatype is sent in request

I have created Flask application in that i am using RequestParser to check datatype of input fields like below

parser = reqparse.RequestParser()
parser.add_argument('article_id',type=str,required=True, help='SUP-REQ-ARTICLEID')
parser.add_argument('description',type=str,required=True, help='SUP-REQ-DESCRIPTION')
parser.add_argument('userid',type=str,required=True, help='SUP-REQ-USERID')


my json input from postman is like below

{
"article_id": 2,
"description":"some description",
"userid":1
}


so in json request first and third field is integer and in request parser the datatype i have mentioned as "str"

when i ran the application and send the request from postman -request is getting processed and not throwing any error in RequestParser validation

Answer

At first, Postman creates a regular HTTP post from your data. And HTTP posts looks like this:

article_id=2&description=some%20description&userid=1

There is no type information, that's plain old URL encoding. Everything is a string in a URL, with & and = as the separators.

All RequestParser can do is convert types for you, from string to something else. That's also why type=str is the default. The parser will simply give you strings for article_id and userid and that's it.

The errors occur when an argument can't be converted to the target type. Set type=int for description and it will give you an error.

Comments