Updating instances#
In this section we’ll see how to update existing instances using DTOData.
PUT handlers#
PUT requests are characterized by requiring the full data model to be submitted for update.
1from __future__ import annotations
2
3from dataclasses import dataclass
4
5from litestar import Litestar, put
6from litestar.dto import DataclassDTO, DTOConfig, DTOData
7from litestar.params import FromPath
8
9
10@dataclass
11class Person:
12 name: str
13 age: int
14 email: str
15 id: int
16
17
18class ReadDTO(DataclassDTO[Person]):
19 config = DTOConfig(exclude={"email"})
20
21
22class WriteDTO(DataclassDTO[Person]):
23 config = DTOConfig(exclude={"id"})
24
25
26@put("/person/{person_id:int}", dto=WriteDTO, return_dto=ReadDTO, sync_to_thread=False)
27def update_person(person_id: FromPath[int], data: DTOData[Person]) -> Person:
28 # Usually the Person would be retrieved from a database
29 person = Person(id=person_id, name="John", age=50, email="email_of_john@example.com")
30 return data.update_instance(person)
31
32
33app = Litestar(route_handlers=[update_person])
This script defines a PUT handler with path /person/{person_id:int} that includes a route parameter,
person_id to specify which person should be updated.
In the handler, we create an instance of Person, simulating a database lookup, and then pass it to the
DTOData.update_instance() method, which returns the same instance
after modifying it with the submitted data.
PATCH handlers#
PATCH requests are characterized by allowing any subset of the properties of the data model to be submitted for update. This is in contrast to PUT requests, which require the entire data model to be submitted.
1from __future__ import annotations
2
3from dataclasses import dataclass
4
5from litestar import Litestar, patch
6from litestar.dto import DataclassDTO, DTOConfig, DTOData
7from litestar.params import FromPath
8
9
10@dataclass
11class Person:
12 name: str
13 age: int
14 email: str
15 id: int
16
17
18class ReadDTO(DataclassDTO[Person]):
19 config = DTOConfig(exclude={"email"})
20
21
22class PatchDTO(DataclassDTO[Person]):
23 config = DTOConfig(exclude={"id"}, partial=True)
24
25
26@patch("/person/{person_id:int}", dto=PatchDTO, return_dto=ReadDTO, sync_to_thread=False)
27def update_person(person_id: FromPath[int], data: DTOData[Person]) -> Person:
28 # Usually the Person would be retrieved from a database
29 person = Person(id=person_id, name="John", age=50, email="email_of_john@example.com")
30 return data.update_instance(person)
31
32
33app = Litestar(route_handlers=[update_person])
In this latest update, the handler has been changed to a @patch()
handler.
This script introduces the PatchDTO class that has a similar configuration to WriteDTO, with the id field
excluded, but it also sets partial=True. This setting allows for
partial updates of the resource.
And here’s a demonstration of use: