Debian Codegraph @

docs/examples/data_transfer_objects/factory/dto_data_problem_statement.py

raw
1 from __future__ import annotations
2
3 from dataclasses import dataclass, field
4 from uuid import UUID, uuid4
5
6 from litestar import Litestar, post
7 from litestar.dto import DataclassDTO, DTOConfig
8
9
10 @dataclass
11 class User:
12 name: str
13 email: str
14 age: int
15 id: UUID = field(default_factory=uuid4)
16
17
18 class UserWriteDTO(DataclassDTO[User]):
19 """Don't allow client to set the id."""
20
21 config = DTOConfig(exclude={"id"})
22
23
24 # We need a dto for the handler to parse the request data per the configuration, however,
25 # we don't need a return DTO as we are returning a dataclass, and Litestar already knows
26 # how to serialize dataclasses.
27 @post("/users", dto=UserWriteDTO, return_dto=None, sync_to_thread=False)
28 def create_user(data: User) -> User:
29 """Create an user."""
30 return data
31
32
33 app = Litestar(route_handlers=[create_user])
34
35 # run: /users -H "Content-Type: application/json" -d '{"name":"Peter","email": "[email protected]", "age":41}'