| 1 |
Our first DTO |
| 2 |
------------- |
| 3 |
In this section we will create our first DTO by extending our script to include a DTO that will ensure we don't expose |
| 4 |
the user's email in the response. |
| 5 |
|
| 6 |
.. literalinclude:: /examples/data_transfer_objects/factory/tutorial/simple_dto_exclude.py |
| 7 |
:language: python |
| 8 |
:caption: ``app.py`` |
| 9 |
:emphasize-lines: 6,16,17,20 |
| 10 |
:linenos: |
| 11 |
|
| 12 |
Here we introduce a new DTO class (``ReadDTO``) and configure it to exclude the ``Person.email`` field. The route |
| 13 |
handler is also instructed to use the DTO to handle the response. |
| 14 |
|
| 15 |
Lets look at these changes in more detail. Firstly, we add two additional imports. |
| 16 |
|
| 17 |
The :class:`DTOConfig <litestar.dto.config.DTOConfig>` class is used to configure DTOs. In this case, we are using it to |
| 18 |
exclude the ``email`` field from the DTO, but there are many other configuration options available and we'll cover most |
| 19 |
of them in this tutorial. |
| 20 |
|
| 21 |
The :class:`DataclassDTO <litestar.dto.dataclass_dto.DataclassDTO>` class is a factory class that specializes |
| 22 |
in creating DTOs from dataclasses. It is also a :class:`Generic <typing.Generic>` class, which means that it accepts |
| 23 |
a type parameter. When we provide a type parameter to a generic class it makes that class a specialized version of the |
| 24 |
generic class. In this case, we create a DTO type that specializes in transferring data to and from instances of the |
| 25 |
``Person`` class (``DataclassDTO[Person]``). |
| 26 |
|
| 27 |
.. note:: |
| 28 |
|
| 29 |
It is not necessary to subclass ``DataclassDTO`` to create a specialized DTO type. For instance, |
| 30 |
``ReadDTO = DataclassDTO[Person]`` also creates a valid, specialized DTO. However, subclassing ``DataclassDTO`` |
| 31 |
allows us to add the configuration object, as well as specialize the type. |
| 32 |
|
| 33 |
Finally, we instruct the route handler to use the DTO (``return_dto=ReadDTO``) to transfer data from the handler |
| 34 |
response. |
| 35 |
|
| 36 |
Lets try it out, again visit `<http://localhost:8000/person/peter>`_ and you should see the following response: |
| 37 |
|
| 38 |
.. image:: images/simple_exclude.png |
| 39 |
:align: center |
| 40 |
|
| 41 |
That's better, now we are not exposing the user's email address! |