Below is a minimal example that showcases the issue.
The context in which this came up for me is that I'm trying to port an existing app which uses FastAPI/SQLModel to Litestar. As illustrated in the SQLModel docs (for example here), I have several pydantic models for read/write/db operations - most of which I would like to ditch in favour of Litestar's DTOs. I accidentally defined my return DTOs using the wrong pydantic model and things weren't working as expected - it would simply ignore the DTO and return the full, unfiltered data.
Since I'm new to the concept of DTOs it took me a while to figure out what the cause of the issue was. For a new user like me it would be very helpful to have Litestar print a prominent warning (if not abort with an error).
No response
from pydantic import BaseModel
from litestar import Litestar, get
from litestar.dto import DTOConfig
from litestar.contrib.pydantic import PydanticDTO
class MyMessage(BaseModel):
msg: str
priority: int
class MyMessage2(BaseModel):
msg: str
priority: int
class ReadDTO(PydanticDTO[MyMessage]):
config = DTOConfig(exclude={"priority"})
@get("/", return_dto=ReadDTO)
async def hello_world() -> MyMessage:
"""Handler function that returns a greeting dictionary."""
return MyMessage(msg="Hello world", priority=1)
app = Litestar(route_handlers=[hello_world])
1. Save the above MCVE as `app.py` and run it via `litestar run`
2. `curl http://127.0.0.1:8008` returns the expected output: `{"msg":"Hello world"}` (note that the `priority` field is correctly stripped by the `return_dto`).
3. In the definition of `ReadDTO`, change `PydanticDTO[MyMessage]` to `PydanticDTO[MyMessage2]`.
4. `curl http://127.0.0.1:8008` now returns the _full_ dictionary including the `priority` field: `{"msg": "Hello world", "priority": 1}`.
This is of course due to the fact that the `hello_world` handler constructs an instance of `MyMessage` while the return DTO is parameterised on `MyMessage2`.
However, there is no warning or any indication that there is a mismatch. Instead, the return DTO is just silently ignored and the full data is returned.
"![SCREENSHOT_DESCRIPTION](SCREENSHOT_LINK.png)"
No response
$ litestar version
2.8.3final0
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too