Object-like validation in classes derived from types.Type


#1

Consider the following:

from apistar import types, validators

class Person(types.Type):
    name = validators.String()
    age = validators.Integer()

i.e., fields name and age are required and additional properties are discarded in a handler like this:

def handler(p: Person) -> dict:

I would like to declare Person in such a way that only name is a required property (age is optional) and all other (different from name and age) properties lead to a ValidationError. I can enforce this using validators.Object on a “non-top-level” property easily as follows:

class Foo(types.Type):
    person = validators.Object(properties={'name': validators.String(),
                                           'age': validators.Integer()},
                               additional_properties=False,
                               required=['name'])

How could I somehow add a validator to Person or whatever to achieve this behavior at the “top-level”, i.e., directly in the Person class?
Thank you in advance!


#2

On ‘Type’ fields are required unless they have a default set. In this example, use ‘default=None’ on the Integer field.


#3

I just tried it, and it turned out that

class Person(types.Type):
    name = validators.String()
    age = validators.Integer(default=None, allow_null=True)

does the job, i.e., age property is not required (and when it is not present, then it is None).
The second problem was not solved with this change, i.e., when I send a request {“name”: “Hugo”, “should_not_be_here”: 123}, then “should_not_be_here” is stripped (not present in the constructed instance of Person. I want to obtain a ValidationError when something like this appears on the input.

Thanks.