pythonflaskflask-restful

Using flask_restful's reqparse, are you able to ignore values not included in params or json?


Let's say you have a request coming for your API and you're using flask_restful.reqparse to handle the parameters and body of request.

POST {{url}}/users
Content-Type: application/json

{
    "firstName": "First",
    "lastName": "Last",
    "age": 25
}
parser = reqparse.RequestParser()
parser.add_argument("firstName", type=str)
parser.add_argument("lastName", type=str)
parser.add_argument("age", type=int)
parser.add_argument("valueInQuestion", type=str)

Is it possible for you to not include values not found in the request when calling .parse_args()? For example, in the parser above we have valueInQuestion but the request body doesn't contain this field.

What I'm getting back from the parser is: {'firstName': 'First', 'lastName': 'Last', 'age': 25, 'valueInQuestion': None}.

What I WANT to get back from the parser is: {'firstName': 'First', 'lastName': 'Last', 'age': 25} because valueInQuestion not included.

EDIT: I know I can filter None values from a dict. I'm not looking to do this because if the user hits a POST request with {...valueInQuestion: null} I want to retain that value, not filter it out.


Solution

  • There is parameter store_missing for Argument constructor - it is set to True by default. By setting this argument to False we get only values passed in request and other parser parameters are just skipped, so we get dictionary without None values. In case anyone is looking for solution, this parameter may help.

    Source: flask-restful/reqparse.py

    Edit:

    reqparse docs say "The whole request parser part of Flask-RESTful is slated for removal and will be replaced by documentation on how to integrate with other packages that do the input/output stuff better (such as marshmallow). This means that it will be maintained until 2.0 but consider it deprecated. Don’t worry, if you have code using that now and wish to continue doing so, it’s not going to go away any time too soon."