noirbizarre / flask-restplus

Fully featured framework for fast, easy and documented API development with Flask
http://flask-restplus.readthedocs.org
Other
2.73k stars 508 forks source link

Having 'strict' fields when using JSON schema models #274

Open apires03 opened 7 years ago

apires03 commented 7 years ago

After creating an JSON Schema model and using it on api.expect(, strict=True). It would only allow fields that are on the schema model and throw error if other args are sent. Similar to "... parse_args() with strict=True ensures that an error is thrown if the request includes arguments your parser does not define." Ex:

address = api.schema_model('Address', { 'properties': { 'road': {'type': 'string'}, }, 'type': 'object' })

@api.route('/address') class AcountInfo(Resource): @api.expect(address, strict=True) def POST(self, account_id):

And if someone tried to send a POST paylod of { "road": "123 South", "city": "Miami" } it would give an error because "city" is not on the schema_model payload

prashker commented 7 years ago

Does #241 accomplish something like what you want? You'd need to fanangle a little more as my code was for a Model and not a schema_model

apires03 commented 7 years ago

Thank you for the workaround!!! Works perfectly.

Minor tweaks for schemas_model. Ex:

from flask_restplus import SchemaModel

api = Namespace(...)

class StrictSchemaModel(SchemaModel):
    # To implement a model that supports strict validation
    # on fields, we need to explicitly add into the schema
    # 'additionalProperties: False'
    # See: https://github.com/noirbizarre/flask-restplus/issues/241
    @property
    def __schema__(self):
        old = super().__schema__
        old['additionalProperties'] = False
        return old

test = StrictSchemaModel('Test', { ... blah blah blah ... })
api.models[test.name] = test