| 1 |
Custom types |
| 2 |
============ |
| 3 |
|
| 4 |
Data serialization / deserialization (encoding / decoding) and validation are important parts of any API framework. |
| 5 |
|
| 6 |
In addition to being capable to encode / decode and validate many standard types, litestar supports Python's builtin dataclasses and libraries like Pydantic and msgspec. |
| 7 |
|
| 8 |
However, sometimes you may need to employ a custom type. |
| 9 |
|
| 10 |
Using type encoders / decoders |
| 11 |
------------------------------ |
| 12 |
|
| 13 |
Litestar supports a mechanism where you provide encoding and decoding hook functions which translate your type in / to a type that it knows. You can provide them via the ``type_encoders`` and ``type_decoders`` :term:`parameters <parameter>` which can be defined on every layer. For example see the :doc:`litestar app reference </reference/app>`. |
| 14 |
|
| 15 |
.. admonition:: Layered architecture |
| 16 |
|
| 17 |
``type_encoders`` and ``type_decoders`` are part of Litestar's layered architecture, which means you can set them on every layer of the application. If you set them on multiple layers, |
| 18 |
the layer closest to the route handler will take precedence. |
| 19 |
|
| 20 |
You can read more about this here: |
| 21 |
:ref:`Layered architecture <usage/applications:layered architecture>` |
| 22 |
|
| 23 |
Here is an example: |
| 24 |
|
| 25 |
.. literalinclude:: /examples/encoding_decoding/custom_type_encoding_decoding.py |
| 26 |
:language: python |
| 27 |
:caption: Tell Litestar how to encode and decode a custom type |
| 28 |
|
| 29 |
Custom Pydantic types |
| 30 |
--------------------- |
| 31 |
|
| 32 |
If you use a custom Pydantic type you can use it directly: |
| 33 |
|
| 34 |
.. literalinclude:: /examples/encoding_decoding/custom_type_pydantic.py |
| 35 |
:language: python |
| 36 |
:caption: Tell Litestar how to encode and decode a custom Pydantic type |