https://docs.litestar.dev/2/usage/requests.html#request-body states that:
The type of data an be any supported type, including
- dataclasses
- TypedDicts
- Pydantic models
- Arbitrary stdlib types
- Typed supported via plugins
More on 1:
By "support for dataclasses/TypedDicts" you'd expect to be able to declare OpenAPI constraints and extra validations somehow, e.g.:
import json
from dataclasses import dataclass, field
from typing import Annotated
from litestar import post
from litestar.app import Litestar
from litestar.params import Parameter, KwargDefinition
@dataclass
class DataBody:
foo1: Annotated[str, Parameter(description="ipsum", gt=1)] = "dummy"
foo2: Annotated[str, Parameter(description="ipsum", gt=1)] = field(default="dummy")
@dataclass
class DictBody:
foo1: Annotated[str, KwargDefinition(description="ipsum", gt=1)]
foo2: Annotated[str, KwargDefinition(default="hello")] # marked as required
@post("/1")
async def handler1(data: DataBody) -> None: ...
@post("/2")
async def handler2(data: DictBody) -> None: ...
app = Litestar([handler1, handler2])
print(json.dumps(app.openapi_schema.to_schema(), indent=4))
The generated OpenAPI schema output is missing default
in many cases (but that's a separate issue, see #3201).
The thing is, how can you:
Pydantic models have Field
, Msgspec has Meta
. Dataclasses have dataclass.field
but you cannot specify OpenAPI constraints through that. TypedDicts don't have that, and cannot even have default values.
It would appear that you can just use Parameter
or KwargDefinition
in TypedDicts and dataclasses as shown in the above snippet, and maybe it (mostly) works? But this should be instructed in the docs (and decision made if that is intended as supported or not). Also, that would allow to define a default also for TypedDict (via KwargDefinition(default=...)
but then that actually doesn't work. Misleading APIs like that should be blocked (although maybe that's a quite special case).
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