8

In my flask-restplus API I'd like not only to check that input data, like in the following example

resource_fields = api.model('Resource', {
    'name': fields.String(default = 'string: name', required = True),
    'state': fields.String(default = 'string: state'),
})

@api.route('/my-resource/<id>')
class MyResource(Resource):
    @api.expect(resource_fields, validate=True)
    def post(self):
        ...

must have 'name' field and may have 'state' field, but also to check that there are no other fields (and to raise an error if this happens). Is there another decorator for this? Can I check the correctness of the input data by a custom function?

pynexj
  • 15,152
  • 5
  • 24
  • 45
user1403546
  • 1,379
  • 1
  • 16
  • 32

3 Answers3

4

Instead of using a dictionary for your fields, try using a RequestParser (flask-restplus accepts both as documented here. That way, you can call parser.parse_args(strict=True) which will throw a 400 Bad Request exception if any unknown fields are present in your input data.

my_resource_parser = api.parser()
my_resource_parser.add_argument('name', type=str, default='string: name', required=True)
my_resource_parser.add_argument('state', type=str, default='string: state')

@api.route('/my-resource/<id>')
class MyResource(Resource):
    def post(self):
        args = my_resource_parser.parse_args(strict=True)
        ...

For more guidance on how to use the request_parser with your resource, check out the ToDo example app in the flask-restplus repo.

shiv
  • 171
  • 7
  • 1
    It seems the payload does not get documented in the Swagger when you build it this way... or am I doing something wrong? How would you user the parser as above but still have the payload description / examples? – Alexis.Rolland Aug 04 '18 at 08:41
  • 1
    Alright I found the answer in the documentation here: http://flask-restplus.readthedocs.io/en/stable/swagger.html#the-api-expect-decorator – Alexis.Rolland Aug 04 '18 at 08:51
  • the problematic issue is the fact that using RequestParser will be DEPRECIATED. https://flask-restplus.readthedocs.io/en/stable/parsing.html – andilabs Jun 01 '20 at 14:30
3

Here is another answer to complete the one from @shiv. The following code snippet allows you to have your payload documented in the Swagger doc generated by Flask Restplus. Taken from the documentation about the expect decorator:

my_resource_parser = api.parser()
my_resource_parser.add_argument('name', type=str, default='string: name', required=True)
my_resource_parser.add_argument('state', type=str, default='string: state')

@api.route('/my-resource/<id>', endpoint='with-parser')
class MyResource(Resource):
    @api.expect(my_resource_parser)
    def post(self):
        args = my_resource_parser.parse_args(strict=True)
        ...
Alexis.Rolland
  • 4,378
  • 3
  • 32
  • 59
2

For those that want to continue using the api.model rather than request parser, it's possible to iterate over your input (assuming list) versus the model. The model behaves like a dictionary.

from flask_restplus import abort

def check_exact(response_list, model):
    for response_dict in response_list:
        for key in response_dict:
            if key not in model:
                abort(400, "Non-specified fields added", field=key)

...

@ns.expect(my_model, validate=True)
def post(self, token):
    """Add new set of responses
    """
    check_exact(api.payload['responses'], my_model)
    ...
  • 1
    why to go through this route, you can easily add `validate=True` to validate – Aqib May 27 '19 at 05:11
  • 1
    Validation doesn't fail on unexpected "extra" keys, which is what brought me to this page. It came as a bit of a surprise. – flayman Sep 02 '19 at 11:58