0

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
Jonathan Tuzman
  • 11,568
  • 18
  • 69
  • 129

1 Answers1

2

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.

  • Interesting, thanks. Do you know of a reference for jsonschema anywhere? Google is being difficult about it... – Jonathan Tuzman Aug 21 '20 at 17:54
  • I guess you can start with json-schema.org . I do not know any quick-start docs, but hope that the following pages will help you: [common keywords of schemas](http://json-schema.org/understanding-json-schema/reference/generic.html); [available types](http://json-schema.org/understanding-json-schema/reference/type.html); [oneOf, anyOf helpers](http://json-schema.org/understanding-json-schema/reference/combining.html) – Andrey Kurilin Aug 22 '20 at 15:22