flask-expects-json icon indicating copy to clipboard operation
flask-expects-json copied to clipboard

Validate against extra fields being supplied

Open rtnolan opened this issue 2 years ago • 2 comments

Hi there,

I've just come across this module and it seems quite useful, a lot simpler to use than other similar modules. I have a schema that looks like this:

register_user_schema = {
    'type': 'object',
    'properties': {
        'userId': {'type': 'string'},
        'name': {'type': 'string'}
    },
    'required': ['userId']
}

Is it possible to throw a validation when extra parameters are being supplied in the body? For example:

POST {
  "userId": "1234",
  "somerandomfield": "blah"
}

This doesn't throw a validation for me even though, somerandomfield isn't in the schema. Is there a way to make it throw an ValidationError?

rtnolan avatar Aug 04 '22 16:08 rtnolan

Hi rtnolan, this library is based on JSON Schema. More specifically it is based on the python implementation of the spec: jsonschema.

You can find the spec here and the documentation for the python package here.

As for extra properties, you can use the flag additionalProperties. Set it to False to disallow them.

In your schema:

register_user_schema = {
    'type': 'object',
    'properties': {
        'userId': {'type': 'string'},
        'name': {'type': 'string'}
    },
    'required': ['userId'],
    'additionalProperties': False
}

Fischerfredl avatar Aug 11 '22 07:08 Fischerfredl

@Fischerfredl thanks for the great reply and fantastic software :) for those playing along at home https://json-schema.org/understanding-json-schema/reference/object.html#additional-properties

dgtlmoon avatar Jan 10 '23 11:01 dgtlmoon