In the python-eve REST API framework I define a list in a resource, the type of the list item is dict. And I don't want the list to be empty. So, how to define the schema?
{
'parents' : {
'type' : 'list',
'schema' : {
'parent' : 'string'
}
}
}
Currently the empty
validation rule is only available for string types, but you can subclass the standard validator to make it capable of processing lists:
from eve.io.mongo import Validator
class MyValidator(Validator):
def _validate_empty(self, empty, field, value):
# let the standard validation happen
super(Validator, self)._validate_empty(empty, field, value)
# add your custom list validation
if isinstance(value, list) and len(value) == 0 and not empty:
self._error(field, "list cannot be empty")
or, if want to provide the standard empty
error message instead:
from eve.io.mongo import Validator
from cerberus import errors
class MyValidator(Validator):
def _validate_empty(self, empty, field, value):
# let the standard validation happen
super(Validator, self)._validate_empty(empty, field, value)
# add your custom list validation
if isinstance(value, list) and len(value) == 0 and not empty:
self._error(field, errors.ERROR_EMPTY_NOT_ALLOWED)
Then you run your API like this:
app = Eve(validator=MyValidator)
app.run()
PS: I plan on adding lists and dicts to Cerberus' empty
rule sometime in the future.