Receiving data#
So far, we’ve only returned data to the client, however, this is only half of the story. We also need to be able to control the data that we receive from the client.
Here’s the code we’ll use to start:
1from __future__ import annotations
2
3from dataclasses import dataclass
4
5from litestar import Litestar, post
6from litestar.dto import DataclassDTO, DTOConfig
7from litestar.params import JSONBody
8
9
10@dataclass
11class Person:
12 name: str
13 age: int
14 email: str
15
16
17class ReadDTO(DataclassDTO[Person]):
18 config = DTOConfig(exclude={"email"})
19
20
21@post("/person", return_dto=ReadDTO, sync_to_thread=False)
22def create_person(data: JSONBody[Person]) -> Person:
23 # Logic for persisting the person goes here
24 return data
25
26
27app = Litestar(route_handlers=[create_person])
To simplify our demonstration, we’ve reduced our data model back down to a single Person class, with name
age and email attributes.
As before, ReadDTO is configured for the handler, and excludes the email attribute from return payloads.
Our handler is now a @post() handler, that is annotated to both accept and return an
instance of Person.
Litestar can natively decode request payloads into Python dataclasses, so we don’t
need a DTO defined for the inbound data for this script to work.
Now that we need to send data to the server to test our program, you can use a tool like Postman or Posting. Here’s an example of a request/response payload: