Debian Codegraph @

docs/validation.md

raw
1 # Validation
2
3 Validation is an important part of deserialization. By default, *apischema* validates types of data according to typing annotations, and [`schema`](json_schema.md#constraints-validation) constraints. But custom validators can also be add for a more precise validation.
4
5 ## Deserialization and validation error
6
7 `ValidationError` is raised when validation fails. This exception contains all the information about the ill-formed part of the data. It can be formatted/serialized using its `errors` property.
8
9 ```python
10 {!validation_error.py!}
11 ```
12
13 As shown in the example, *apischema* will not stop at the first error met but tries to validate all parts of the data.
14
15 !!! note
16 `ValidationError` can also be serialized using `apischema.serialize` (this will use `errors` internally).
17
18 ## Constraint errors customization
19
20 Constraints are validated at deserialization, with *apischema* providing default error messages.
21 Messages can be customized by setting the corresponding attribute of `apischema.settings.errors`. They can be either a string which will be formatted with the constraint value (using `str.format`), e.g. `less than {} (minimum)`, or a function with 2 parameters: the constraint value and the invalid data.
22
23 ```python
24 {!settings_errors.py!}
25 ```
26
27 !!! note
28 Default error messages doesn't include the invalid data for security reason (data could for example be a password too short).
29
30 !!! note
31 Other error message can be customized, for example `missing property` for missing required properties, etc.
32
33 ## Dataclass validators
34
35 Dataclass validation can be completed by custom validators. These are simple decorated methods which will be executed during validation, after all fields having been deserialized.
36
37 !!! note
38 Previously to v0.17, validators could raise arbitrary exceptions (except AssertionError of course); see [FAQ](#why-validators-cannot-raise-arbitrary-exception) for the reason of this change.
39
40 ```python
41 {!validator.py!}
42 ```
43
44 !!! warning
45 **DO NOT use `assert`** statement to validate external data, ever. In fact, this statement is made to be disabled when executed in optimized mode (see [documentation](https://docs.python.org/3/reference/simple_stmts.html#the-assert-statement)), so validation would be disabled too. This warning doesn't concern only *apischema*; `assert` is only for internal assertion in debug/development environment. That's why *apischema* will not catch `AssertionError` as a validation error but reraises it, making `deserialize` fail.
46
47 !!! note
48 Validators are always executed in order of declaration.
49
50 ### Automatic dependency management
51
52 It makes no sense to execute a validator using a field that is ill-formed. Hopefully, *apischema* is able to compute validator dependencies — the fields used in validator; validator is executed only if the all its dependencies are ok.
53
54 ```python
55 {!computed_dependencies.py!}
56 ```
57
58 !!! note
59 Despite the fact that validator uses the `self` argument, it can be called during validation even if all the fields of the class are not ok and the class not really instantiated. In fact, instance is kind of mocked for validation with only the needed field.
60
61 ### Raise more than one error with `yield`
62
63 Validation of a list field can require raising several exceptions, one for each bad element. With `raise`, this is not possible, because you can raise only once.
64
65 However, *apischema* provides a way of raising as many errors as needed by using `yield`. Moreover, with this syntax, it is possible to add a "path" (see [below](#error-path)) to the error to precise its location in the validated data. This path will be added to the `loc` key of the error.
66
67 ```python
68 {!validator_yield.py!}
69 ```
70
71 #### Error path
72
73 In the example, the validator yields a tuple of an "error path" and the error message. Error path can be:
74
75 - a field alias (obtained with `apischema.objects.get_alias`);
76 - an integer, for list indices;
77 - a raw string, for dict key (or field);
78 - an `apischema.objects.AliasedStr`, a string subclass which will be aliased by deserialization aliaser;
79 - an iterable, e.g. a tuple, of this 4 components.
80
81 `yield` can also be used with only an error message.
82
83 !!! note
84 For dataclass field error path, it's advised to use `apischema.objects.get_alias` instead of raw string, because it will take into account potential aliasing and it will be better handled by IDE (refactoring, cross-referencing, etc.)
85
86 ### Discard
87
88 If one of your validators fails because a field is corrupted, maybe you don't want subsequent validators to be executed. `validator` decorator provides a `discard` parameter to discard fields of the remaining validation. All the remaining validators having discarded fields in [dependencies](#automatic-dependencies-management) will not be executed.
89
90 ```python
91 {!discard.py!}
92 ```
93
94 You can notice in this example that *apischema* tries to avoid using raw strings to identify fields. In every function of the library using fields identifier (`apischema.validator`, `apischema.dependent_required`, `apischema.fields.set_fields`, etc.), you have always three ways to pass them:
95 - using field object, preferred in dataclass definition;
96 - using `apischema.objects.get_field`, to be used outside of class definition; it works with `NamedTuple` too — the object returned is the *apischema* internal field representation, common to `dataclass`, `NamedTuple` and `TypedDict`;
97 - using raw strings, thus not handled by static tools like refactoring, but it works;
98
99 ### Field validators
100
101 #### At field level
102 Fields are validated according to their types and schema. But it's also possible to add validators to fields.
103
104 ```python
105 {!field_validator.py!}
106 ```
107
108 When validation fails for a field, it is discarded and cannot be used in class validators, as is the case when field schema validation fails.
109
110 !!! note
111 `field_validator` allows reusing the the same validator for several fields. However in this case, using a custom type (for example a `NewType`) with validators (see [next section](#validators-for-every-new-types)) could often be a better solution.
112
113 #### Using other fields
114
115 A common pattern can be to validate a field using other fields values. This is achieved with dataclass validators seen above. However, there is a shortcut for this use case:
116
117 ```python
118 {!validator_field.py!}
119 ```
120
121 ### Validators inheritance
122
123 Validators are inherited just like other class fields.
124
125 ```python
126 {!validator_inheritance.py!}
127 ```
128
129 ### Validator with `InitVar`
130
131 Dataclasses `InitVar` are accessible in validators by using parameters the same way `__post_init__` does. Only the needed fields have to be put in parameters, they are then added to validator dependencies.
132
133 ```python
134 {!validator_post_init.py!}
135 ```
136
137 ### Validators are not run on default values
138 If all validator dependencies are initialized with their default values, they are not run.
139
140 ```python
141 {!validator_default.py!}
142 ```
143
144 ## Validators for every type
145
146 Validators can also be declared as regular functions, in which case annotation of the first param is used to associate it to the validated type (you can also use the `owner` parameter); this allows adding a validator to every type.
147
148 Last but not least, validators can be embedded directly into `Annotated` arguments using `validators` metadata.
149
150 ```python
151 {!validator_function.py!}
152 ```
153
154 ## FAQ
155
156 #### How are validator dependencies computed?
157
158 `ast.NodeVisitor` and the Python black magic begins...
159
160 #### Why only validate at deserialization and not at instantiation?
161 *apischema* uses type annotations, so every objects used can already be statically type-checked (with *Mypy*/*Pycharm*/etc.) at instantiation but also at modification.
162
163 #### Why use validators for dataclasses instead of doing validation in `__post_init__`?
164 Actually, validation can completely be done in `__post_init__`, there is no problem with that. However, validators offers one thing that cannot be achieved with `__post_init__`: they are run before `__init__`, so they can validate incomplete data. Moreover, they are only run during deserialization, so they don't add overhead to normal class instantiation.
165
166 #### Why validators cannot raise arbitrary exception?
167
168 Allowing arbitrary exception is in fact a security issue, because unwanted exception could be raised, and their message displayed in validation error. It could either contain sensitive data, or give information about the implementation which could be used to hack it.
169
170 By the way, it's possible to define a decorator to convert precise exceptions to `ValidationError`:
171 ```python
172 from collections.abc import Callable
173 from functools import wraps
174 from typing import TypeVar
175 from apischema import ValidationError
176
177 Func = TypeVar("Func", bound=Callable)
178 def catch(*exceptions) -> Callable[[Func], Func]:
179 def decorator(func: Func) -> Func:
180 @wraps(func)
181 def wrapper(*args, **kwargs):
182 try:
183 return func(*args, **kwargs)
184 except Exception as err:
185 raise ValidationError(str(err)) if isinstance(err, exceptions) else err
186 return wrapper
187 return decorator
188 ```