Debian Codegraph @

docs/conversions.md

raw
1 # Conversions – (de)serialization customization
2
3 *apischema* covers the majority of standard data types, but of course that's not enough, which is why it enables you to add support for all your classes and the libraries you use.
4
5 Actually, *apischema* itself uses this conversion feature to provide a basic support for standard library data types like UUID/datetime/etc. (see [std_types.py](https://github.com/wyfo/apischema/blob/master/apischema/std_types.py))
6
7 ORM support can easily be achieved with this feature (see [SQLAlchemy example](examples/sqlalchemy_support.md)).
8
9 In fact, you can even add support for competitor libraries like *Pydantic* (see [*Pydantic* compatibility example](examples/pydantic_support.md))
10
11 ## Principle - apischema conversions
12
13 An *apischema* conversion is composed of a source type, let's call it `Source`, a target type `Target` and a converter function with signature `(Source) -> Target`.
14
15 When a class (actually, a non-builtin class, so not `int`/`list`/etc.) is deserialized, *apischema* will check if there is a conversion where this type is the target. If found, the source type of conversion will be deserialized, then the converter will be applied to get an object of the expected type. Serialization works the same way but inverted: look for a conversion with type as source, apply then converter, and get the target type.
16
17 Conversions are also handled in schema generation: for a deserialization schema, source schema is merged to target schema, while target schema is merged to source schema for a serialization schema.
18
19
20 ## Register a conversion
21
22 Conversion is registered using `apischema.deserializer`/`apischema.serializer` for deserialization/serialization respectively.
23
24 When used as function decorator, the `Source`/`Target` types are directly extracted from the conversion function signature.
25
26 `serializer` can be called on methods/properties, in which case `Source` type is inferred to be the owning type.
27
28 ```python
29 {!conversions.py!}
30 ```
31
32 !!! warning
33 (De)serializer methods cannot be used with `typing.NamedTuple`; in fact, *apischema* uses the `__set_name__` magic method but it is not called on `NamedTuple` subclass fields.
34
35 ### Multiple deserializers
36
37 Sometimes, you want to have several possibilities to deserialize a type. If it's possible to register a deserializer with a `Union` param, it's not very practical. That's why *apischema* make it possible to register several deserializers for the same type. They will be handled with a `Union` source type (ordered by deserializers registration), with the right serializer selected according to the matching alternative.
38
39 ```python
40 {!multiple_deserializers.py!}
41 ```
42
43 On the other hand, serializer registration overwrites the previous registration if any.
44
45 `apischema.conversions.reset_deserializers`/`apischema.conversions.reset_serializers` can be used to reset (de)serializers (even those of the standard types embedded in *apischema*)
46
47 ### Inheritance
48
49 All serializers are naturally inherited. In fact, with a conversion function `(Source) -> Target`, you can always pass a subtype of `Source` and get a `Target` in return.
50
51 Moreover, when serializer is a method/property, overriding this method/property in a subclass will override the inherited serializer.
52
53 ```python
54 {!serializer_inheritance.py!}
55 ```
56
57 !!! note
58 Inheritance can also be toggled off in specific cases, like in the [Class as union of its subclasses](examples/subclass_union.md) example
59
60 On the other hand, deserializers cannot be inherited, because the same `Source` passed to a conversion function `(Source) -> Target` will always give the same `Target` (not ensured to be the desired subtype).
61
62 !!! note
63 Pseudo-inheritance could be achieved by registering a conversion (using for example a `classmethod`) for each subclass in `__init_subclass__` method (or a metaclass), or by using `__subclasses__`; see [example](examples/inherited_deserializer.md)
64
65
66 ## Generic conversions
67
68 `Generic` conversions are supported out of the box.
69
70 ```python
71 {!generic_conversions.py!}
72 ```
73
74 However, you're not allowed to register a conversion of a specialized generic type, like `Foo[int]`.
75
76 ## Conversion object
77
78 In the previous example, conversions were registered using only converter functions. However, it can also be done by passing a `apischema.conversions.Conversion` instance. It allows specifying additional metadata to conversion (see [next sections](#sub-conversions) for examples) and precise converter source/target when annotations are not available.
79
80 ```python
81 {!conversion_object.py!}
82 ```
83
84 ## Dynamic conversions — select conversions at runtime
85
86 Whether or not a conversion is registered for a given type, conversions can also be provided at runtime, using the `conversion` parameter of `deserialize`/`serialize`/`deserialization_schema`/`serialization_schema`.
87
88 ```python
89 {!dynamic_conversions.py!}
90 ```
91
92 !!! note
93 For `definitions_schema`, conversions can be added with types by using a tuple instead, for example `definitions_schema(serializations=[(list[Foo], foo_to_bar)])`.
94
95 The `conversion` parameter can also take a tuple of conversions, when you have a `Union`, a `tuple` or when you want to have several deserializations for the same type.
96
97
98 ### Dynamic conversions are local
99
100 Dynamic conversions are discarded after having been applied (or after class without conversion having been encountered). For example, you can't apply directly a dynamic conversion to a dataclass field when calling `serialize` on an instance of this dataclass. Reasons for this design are detailed in the [FAQ](#whats-the-difference-between-conversion-and-default_conversion-parameters).
101
102 ```python
103 {!local_conversions.py!}
104 ```
105
106 !!! note
107 Dynamic conversion is not discarded when the encountered type is a container (`list`, `dict`, `Collection`, etc. or `Union`) or a registered conversion from/to a container; the dynamic conversion can then apply to the container elements
108
109 ### Dynamic conversions interact with `type_name`
110
111 Dynamic conversions are applied before looking for a ref registered with `type_name`
112
113 ```python
114 {!dynamic_type_name.py!}
115 ```
116
117 ### Bypass registered conversion
118
119 Using `apischema.identity` as a dynamic conversion allows you to bypass a registered conversion, i.e. to (de)serialize the given type as it would be without conversion registered.
120
121 ```python
122 {!bypass_conversions.py!}
123 ```
124
125 !!! note
126 For a more precise selection of bypassed conversion, for `tuple` or `Union` member for example, it's possible to pass the concerned class as the source *and* the target of conversion *with* `identity` converter, as shown in the example.
127
128 ### Liskov substitution principle
129
130 LSP is taken into account when applying dynamic conversion: the serializer source can be a subclass of the actual class and the deserializer target can be a superclass of the actual class.
131
132 ```python
133 {!dynamic_conversions_lsp.py!}
134 ```
135
136 ### Generic dynamic conversions
137
138 `Generic` dynamic conversions are supported out of the box. Also, contrary to registered conversions, partially specialized generics are allowed.
139
140 ```python
141 {!dynamic_generic_conversions.py!}
142 ```
143
144 ## Field conversions
145
146 It is possible to register a conversion for a particular dataclass field using `conversion` metadata.
147
148 ```python
149 {!field_conversions.py!}
150 ```
151
152 !!! note
153 It's possible to pass a conversion only for deserialization or only for serialization
154
155 ## Serialized method conversions
156
157 Serialized methods can also have dedicated conversions for their return
158
159 ```python
160 {!serialized_conversions.py!}
161 ```
162
163
164 ## Default conversions
165
166 As with almost every default behavior in *apischema*, default conversions can be configured using `apischema.settings.deserialization.default_conversion`/`apischema.settings.serialization.default_conversion`. The initial value of these settings are the function which retrieved conversions registered with `deserializer`/`serializer`.
167
168 You can for example [support *attrs*](examples/attrs_support.md) classes with this feature:
169
170 ```python
171 {!examples/attrs_support.py!}
172 ```
173
174 *apischema* functions (`deserialize`/`serialize`/`deserialization_schema`/`serialization_schema`/`definitions_schema`) also have a `default_conversion` parameter to dynamically modify default conversions. See [FAQ](#whats-the-difference-between-conversion-and-default_conversion-parameters) for the difference between `conversion` and `default_conversion` parameters.
175
176 ## Sub-conversions
177
178 Sub-conversions are [dynamic conversions](#dynamic-conversions--select-conversions-at-runtime) applied on the result of a conversion.
179
180 ```python
181 {!sub_conversions.py!}
182 ```
183
184 Sub-conversions can also be used to [bypass registered conversions](#bypass-registered-conversion) or to define [recursive conversions](#lazyrecursive-conversions).
185
186 ## Lazy/recursive conversions
187
188 Conversions can be defined lazily, i.e. using a function returning `Conversion` (single, or a tuple of it); this function must be wrapped into a `apischema.conversions.LazyConversion` instance.
189
190 It allows creating recursive conversions or using a conversion object which can be modified after its definition (for example a conversion for a base class modified by `__init_subclass__`)
191
192 It is used by *apischema* itself for the generated JSON schema. It is indeed a recursive data, and the [different versions](json_schema.md#json-schema--openapi-version) are handled by a conversion with a lazy recursive sub-conversion.
193
194 ```python
195 {!recursive_conversions.py!}
196 ```
197
198 ### Lazy registered conversions
199
200 Lazy conversions can also be registered, but the deserialization target/serialization source has to be passed too.
201
202 ```python
203 {!lazy_registered_conversion.py!}
204 ```
205
206 ## Conversion helpers
207
208 ### String conversions
209
210 A common pattern of conversion concerns classes that have a string constructor and a `__str__` method, for example standard types `uuid.UUID`, `pathlib.Path`, or `ipaddress.IPv4Address`. Using `apischema.conversions.as_str` will register a string-deserializer from the constructor and a string-serializer from the `__str__` method. `ValueError` raised by the constructor is caught and converted to `ValidationError`.
211
212 ```python
213 {!as_str.py!}
214 ```
215
216 !!! note
217 Previously mentioned standard types are handled by *apischema* using `as_str`.
218
219 ### ValueErrorCatching
220
221 Converters can be wrapped with `apischema.conversions.catch_value_error` in order to catch `ValueError` and reraise it as a `ValidationError`. It's notably used but `as_str` and other standard types.
222
223 !!! note
224 This wrapper is in fact inlined in deserialization, so it has better performance than writing the *try-catch* in the code.
225
226 ### Use `Enum` names
227
228 `Enum` subclasses are (de)serialized using values. However, you may want to use enumeration names instead, that's why *apischema* provides `apischema.conversion.as_names` to decorate `Enum` subclasses.
229
230 ```python
231 {!as_names.py!}
232 ```
233
234 ### Class as union of its subclasses
235
236
237
238
239 ### Object deserialization — transform function into a dataclass deserializer
240
241 `apischema.objects.object_deserialization` can convert a function into a new function taking a unique parameter, a dataclass whose fields are mapped from the original function parameters.
242
243 It can be used for example to build a deserialization conversion from an alternative constructor.
244
245 ```python
246 {!object_deserialization.py!}
247 ```
248
249 !!! note
250 Parameters metadata can be specified using `typing.Annotated`, or be passed with `parameters_metadata` parameter, which is a mapping of parameter names as key and mapped metadata as value.
251
252 ### Object serialization — select only a subset of fields
253
254 `apischema.objects.object_serialization` can be used to serialize only a subset of an object fields and methods.
255
256 ```python
257 {!object_serialization.py!}
258 ```
259
260 ## FAQ
261
262 #### What's the difference between `conversion` and `default_conversion` parameters?
263
264 Dynamic conversions (`conversion` parameter) exists to ensure consistency and reuse of subschemas referenced (with a `$ref`) in the JSON/OpenAPI schema.
265
266 In fact, different global conversions (`default_conversion` parameter) could lead to having a field with different schemas depending on global conversions, so a class would not be able to be referenced consistently. Because dynamic conversions are local, they cannot mess with an object field schema.
267
268 Schema generation uses the same default conversions for all definitions (which can have associated dynamic conversion).
269
270 `default_conversion` parameter allows having different (de)serialization contexts, for example to map date to string between frontend and backend, and to timestamp between backend services.