| 1 |
from dataclasses import dataclass |
| 2 |
from uuid import UUID, uuid4 |
| 3 |
|
| 4 |
from litestar import Litestar, post |
| 5 |
from litestar.dto import DataclassDTO, DTOConfig, DTOData |
| 6 |
|
| 7 |
|
| 8 |
@dataclass |
| 9 |
class User: |
| 10 |
name: str |
| 11 |
email: str |
| 12 |
age: int |
| 13 |
id: UUID |
| 14 |
|
| 15 |
|
| 16 |
class UserWriteDTO(DataclassDTO[User]): |
| 17 |
"""Don't allow client to set the id.""" |
| 18 |
|
| 19 |
config = DTOConfig(exclude={"id"}) |
| 20 |
|
| 21 |
|
| 22 |
@post("/users", dto=UserWriteDTO, return_dto=None, sync_to_thread=False) |
| 23 |
def create_user(data: DTOData[User]) -> User: |
| 24 |
"""Create an user.""" |
| 25 |
return data.create_instance(id=uuid4()) |
| 26 |
|
| 27 |
|
| 28 |
app = Litestar(route_handlers=[create_user]) |
| 29 |
|
| 30 |
# run: /users -H "Content-Type: application/json" -d '{"name":"Peter", "email": "[email protected]", "age":41}' |