Debian Codegraph @

docs/de_serialization.md

raw
1 # (De)serialization
2
3 *apischema* aims to help with deserialization/serialization of API data, mostly JSON.
4
5 Let's start again with the [overview example](index.md#example)
6 ```python
7 {!quickstart.py!}
8 ```
9
10 ## Deserialization
11
12 `apischema.deserialize` deserializes Python types from JSON-like data: `dict`/`list`/`str`/`int`/`float`/`bool`/`None` — in short, what you get when you execute `json.loads`. Types can be dataclasses as well as `list[int]`, `NewType`s, or whatever you want (see [conversions](conversions.md) to extend deserialization support to every type you want).
13
14 ```python
15 {!deserialization.py!}
16 ```
17
18 Deserialization performs a validation of data, based on typing annotations and other information (see [schema](json_schema.md) and [validation](validation.md)).
19
20 ### Deserialization passthrough
21
22 In some case, e.g. MessagePack loading with raw bytes inside, some data will have other type than
23 JSON primitive ones. These types can be allowed using `pass_through` parameter; it must be collection of classes, or a predicate. Behavior can also be set globally using `apischema.settings.deserialization.pass_through`.
24
25 Only non JSON primitive classes can be allowed, because *apischema* relies on a type check with `isinstance` to skip deserialization. That exclude `NewType` but also `TypeDict`.
26
27 ```python
28 {!deserialization_pass_through.py!}
29 ```
30
31 !!! note
32 Equivalent serialization feature is presented in [optimizations documentation](optimizations_and_benchmark.md#serialization-passthrough).
33
34 ### Strictness
35
36 #### Coercion
37
38 *apischema* is strict by default. You ask for an integer, you have to receive an integer.
39
40 However, in some cases, data has to be be coerced, for example when parsing a configuration file. That can be done using `coerce` parameter; when set to `True`, all primitive types will be coerced to the expected type of the data model like the following:
41
42 ```python
43 {!coercion.py!}
44 ```
45
46 `bool` can be coerced from `str` with the following case-insensitive mapping:
47
48 | False | True |
49 | --- | --- |
50 | 0 | 1 |
51 | f | t |
52 | n | y |
53 | no | yes |
54 | false | true |
55 | off | on |
56 | ko | ok |
57
58 The `coerce` parameter can also receive a coercion function which will then be used instead of default one.
59
60 ```python
61 {!coercion_function.py!}
62 ```
63
64 !!! note
65 If coercer result is not an instance of class passed in argument, a ValidationError will be raised with an appropriate error message
66
67 !!! warning
68 Coercer first argument is a primitive json type `str`/`bool`/`int`/`float`/`list`/`dict`/`type(None)`; it can be `type(None)`, so returning `cls(data)` will fail in this case.
69
70 #### Additional properties
71
72 *apischema* is strict too about the number of fields received for an *object*. In JSON schema terms, *apischema* put `"additionalProperties": false` by default (this can be configured by class with [properties field](#additional-and-pattern-properties)).
73
74 This behavior can be controlled by `additional_properties` parameter. When set to `True`, it prevents the rejection of unexpected properties.
75
76 ```python
77 {!additional_properties.py!}
78 ```
79
80 #### Fall back on default
81
82 Validation errors can happen when deserializing an ill-formed field. However, if this field has a default value/factory, deserialization can fall back on this default; this is enabled by `fall_back_on_default` parameter. This behavior can also be configured for each field using metadata.
83
84 ```python
85 {!fall_back_on_default.py!}
86 ```
87
88 #### Strictness configuration
89
90 *apischema* global configuration is managed through `apischema.settings` object.
91 It has, among other, three global variables `settings.additional_properties`, `settings.deserialization.coerce` and `settings.deserialization.fall_back_on_default` whose values are used as default parameter values for the `deserialize`; by default, `additional_properties=False`, `coerce=False` and `fall_back_on_default=False`.
92
93 !!! note
94 `additional_properties` settings is in `settings.deserialization` because it's also used in [serialization]().
95
96 Global coercion function can be set with `settings.coercer` following this example:
97
98 ```python
99 import json
100 from apischema import ValidationError, settings
101
102 prev_coercer = settings.coercer
103
104 def coercer(cls, data):
105 """In case of coercion failures, try to deserialize json data"""
106 try:
107 return prev_coercer(cls, data)
108 except ValidationError as err:
109 if not isinstance(data, str):
110 raise
111 try:
112 return json.loads(data)
113 except json.JSONDecodeError:
114 raise err
115
116 settings.coercer = coercer
117 ```
118
119 ## Fields set
120
121 Sometimes, it can be useful to know which field has been set by the deserialization, for example in the case of *PATCH* requests, to know which field has been updated. Moreover, it is also used in serialization to limit the fields serialized (see [next section](#exclude-unset-fields))
122
123 Because *apischema* use vanilla dataclasses, this feature is not enabled by default and must be set explicitly on a per-class basis. *apischema* provides a simple API to get/set this metadata.
124
125 ```python
126 {!fields_set.py!}
127 ```
128
129 !!! warning
130 The `with_fields_set` decorator MUST be put above `dataclass` one. This is because both of them modify `__init__` method, but only the first is built to take the second in account.
131
132 !!! warning
133 `dataclasses.replace` works by setting all the fields of the replaced object. Because of this issue, *apischema* provides a little wrapper `apischema.dataclasses.replace`.
134
135
136 ## Serialization
137
138 `apischema.serialize` is used to serialize Python objects to JSON-like data. Contrary to `apischema.deserialize`, Python type can be omitted; in this case, the object will be serialized with an `typing.Any` type, i.e. the class of the serialized object will be used.
139
140 ```python
141 {!serialization.py!}
142 ```
143
144 !!! note
145 Omitting type with `serialize` can have unwanted side effects, as it makes loose any type annotations of the serialized object. In fact, generic specialization as well as PEP 593 annotations cannot be retrieved from an object instance; [conversions](conversions.md) can also be impacted
146
147 That's why it's advisable to pass the type when it is available.
148
149 ### Type checking
150
151 Serialization can be configured using `check_type` (default to `False`) and `fall_back_on_any` (default to `False`) parameters. If `check_type` is `True`, the serialized object type will be checked to match the serialized type.
152 If it doesn't, `fall_back_on_any` allows bypassing the serialized type to use `typing.Any` instead, i.e. to use the serialized object class.
153
154 The default values of these parameters can be modified through `apischema.settings.serialization.check_type` and `apischema.settings.serialization.fall_back_on_any`.
155
156 !!! note
157 *apischema* relies on typing annotations, and assumes that the code is well statically type-checked. That's why it doesn't add the overhead of type checking by default (it's more than 10% performance impact).
158
159 ### Serialized methods/properties
160
161 *apischema* can execute methods/properties during serialization and add the computed values with the other fields values; just put `apischema.serialized` decorator on top of methods/properties you want to be serialized.
162
163 The function name is used unless an alias is given in decorator argument.
164
165 ```python
166 {!serialized.py!}
167 ```
168
169 !!! note
170 Serialized methods must not have parameters without default, as *apischema* needs to execute them without arguments
171
172 !!! note
173 Overriding of a serialized method in a subclass will also override the serialization of the subclass.
174
175 #### Error handling
176
177 Errors occurring in serialized methods can be caught in a dedicated error handler registered with `error_handler` parameter. This function takes in parameters the exception, the object and the alias of the serialized method; it can return a new value or raise the current or another exception — it can for example be used to log errors without throwing the complete serialization.
178
179 The resulting serialization type will be a `Union` of the normal type and the error handling type; if the error handler always raises, use [`typing.NoReturn`](https://docs.python.org/3/library/typing.html#typing.NoReturn) annotation.
180
181 `error_handler=None` correspond to a default handler which only return `None` — exception is thus discarded and serialization type becomes `Optional`.
182
183 The error handler is only executed by *apischema* serialization process, it's not added to the function, so this one can be executed normally and raise an exception in the rest of your code.
184
185 ```python
186 {!serialized_error.py!}
187 ```
188
189 #### Non-required serialized methods
190
191 Serialized methods (or their error handler) can return `apischema.Undefined`, in which case the property will not be included into the serialization; accordingly, the property loses the *required* qualification in the JSON schema.
192
193 ```python
194 {!serialized_undefined.py!}
195 ```
196
197 #### Generic serialized methods
198
199 Serialized methods of generic classes get the right type when their owning class is specialized.
200
201 ```python
202 {!serialized_generic.py!}
203 ```
204
205 ### Exclude unset fields
206
207 When a class has a lot of optional fields, it can be convenient to not include all of them, to avoid a bunch of useless fields in your serialized data.
208 Using the previous feature of [fields set tracking](#fields-set), `serialize` can exclude unset fields using its `exclude_unset` parameter or `settings.serialization.exclude_unset` (default is `True`).
209
210 ```python
211 {!exclude_unset.py!}
212 ```
213
214 !!! note
215 As written in comment in the example, `with_fields_set` is necessary to benefit from the feature. If the dataclass don't use it, the feature will have no effect.
216
217 Sometimes, some fields must be serialized, even with their default value; this behavior can be enforced using field metadata. With it, a field will be marked as set even if its default value is used at initialization.
218
219 ```python
220 {!default_as_set.py!}
221 ```
222
223 !!! note
224 This metadata has effect only in combination with `with_fields_set` decorator.
225
226 ### Exclude fields with default value or `None`
227
228 Fields metadata [`apischema.skip`](data_model.md#skip-field-serialization-depending-on-condition) already allows skipping fields serialization depending on a condition, for example if the field is `None` or equal to its default value. However, it must be added on each concerned fields, and that can be tedious when you want to set that behavior globally.
229
230 That's why *apischema* provides the two following settings:
231
232 - `settings.serialization.exclude_defaults`: whether fields which are equal to their default values should be excluded from serialization; default `False`
233 - `settings.serialization.exclude_none`: whether fields which are equal to `None` should be excluded from serialization; default `False`
234
235 These settings can also be set directly using `serialize` parameters, like in the following example:
236
237 ```python
238 {!exclude_defaults_none.py!}
239 ```
240
241 ### Field ordering
242
243 Usually, JSON object properties are unordered, but sometimes, order does matter. By default, fields, are ordered according to their declaration; serialized methods are appended after the fields.
244
245 However, it's possible to change the ordering using `apischema.order`.
246
247 #### Class-level ordering
248
249 `order` can be used to decorate a class with the field ordered as expected:
250
251 ```python
252 {!class_ordering.py!}
253 ```
254
255 #### Field-level ordering
256
257 Each field has an order "value" (0 by default), and ordering is done by sorting fields using this value; if several fields have the same order value, they are sorted by their declaration order. For instance, assigning `-1` to a field will put it before every other fields, and `999` will surely put it at the end.
258
259 This order value is set using `order`, this time as a field metadata (or passed to `order` argument of [serialized methods/properties](#serialized-methodsproperties)). It has the following overloaded signature:
260
261 - `order(value: int, /)`: set the order value of the field
262 - `order(*, after)`: ignore the order value and put the field after the given field/method/property
263 - `order(*, before)`: ignore the order value and put the field before the given field/method/property
264
265 !!! note
266 `after` and `before` can be raw strings, but also dataclass fields, methods or properties.
267
268 Also, `order` can again be used as class decorator to override ordering metadata, by passing this time a mapping of field with their overridden order.
269
270 ```python
271 {!ordering.py!}
272 ```
273
274
275 ### TypedDict additional properties
276
277 `TypedDict` can contain additional keys, which are not serialized by default. Setting `additional_properties` parameter to `True` (or `apischema.settings.additional_properties`) will toggle on their serialization (without aliasing).
278
279
280 ## FAQ
281
282 #### Why isn't coercion the default behavior?
283 Because ill-formed data can be symptomatic of deeper issues, it has been decided that highlighting them would be better than hiding them. By the way, this is easily globally configurable.
284
285 #### Why isn't `with_fields_set` enabled by default?
286 It's true that this feature has the little cost of adding a decorator everywhere. However, keeping dataclass decorator allows IDEs/linters/type checkers/etc. to handle the class as such, so there is no need to develop a plugin for them. Standard compliance can be worth the additional decorator. (And little overhead can be avoided when not useful)
287
288 #### Why isn't serialization type checking enabled by default?
289
290 Type checking has a runtime cost, which means poorer performance. Moreover, as explained in [performances section](optimizations_and_benchmark.md#serialization-passthrough), it prevents "passthrough" optimization. At last, code is supposed to be statically verified, and thus types already checked. (If some silly things are done and leads to have unsupported types passed to the JSON library, an error will be raised anyway).
291
292 Runtime type checking is more a development feature, which could for example be with `apischema.settings.serialization.check_type = __debug__`.
293
294 #### Why not use json library `default` fallback parameter for serialization?
295 Some *apischema* features like [conversions](conversions.md) can simply not be implemented with `default` fallback. By the way, *apischema* can perform [surprisingly better](optimizations_and_benchmark.md#passing-through-is-not-always-faster) than using `default`.
296
297 However, `default` can be used in combination with [passthrough optimization](optimizations_and_benchmark.md#serialization-passthrough) when needed to improve performance.