Search code examples
flaskflask-restplusflask-restx

Only allow expected fields?


My model expects two fields, and I validate my endpoint with that model:

config_model = api.model('Configuration', {
    'cuvettes_count': fields.Integer,
    'pipettes_count': fields.Integer
})

# later
class ConfigEndpoint(Resource):
    @config_endpoint.expect(config_model, validate=True)
    def put(self):

How do I:

  1. Raise a validation error if a key besides the two specified is present
  2. Raise a validation error if neither of the keys are present, but only require one at a time

Solution

  • Raise a validation error if a key besides the two specified is present

    Currently, flask-restx doesn't allow it out of the box. The following PR should add the feature. You can try to adopt the PR to your code even now by creating a custom Model class with proposed changes.

    Raise a validation error if neither of the keys are present, but only require one at a time

    I guess the easiest way is to use jsonschema directly, i.e something like bellow

    config_model = api.schema_model('Configuration', {
        'type': 'object',
        'properties': {
            'cuvettes_count': {'type': 'integer'},
            'pipettes_count': {'type': 'integer'}
        },
        'anyOf': [{'required': ['cuvettes_count']}, {'required': ['pipettes_count']}]
    })
    

    Unfortunately, this will work only for the validating of input data and do not work for marshaling responses.