#Bad request when using msgspec.Struct instead of Pydantic, dataclass or attrs

1 messages · Page 1 of 1 (latest)

serene jungle
#

Hi guys,

i tried different dataclass libs for model definition. Using msgspec.Struct, results in a bad (post) request although it works when using Pydantic, dataclass or attrs. To reproduce this error, comment all models expect one.

from pydantic import BaseModel
from dataclasses import dataclass
from msgspec import Struct
from attrs import define
from litestar import get, Litestar, post

class Resource(BaseModel):
    id: int
    name: str

@dataclass
class Resource:
    id: int
    name: str

@define
class Resource:
    id: int
    name: str

class Resource(Struct):
    id: int
    name: str

@get("/resources")
async def retrieve_resource() -> Resource:
    return Resource(id=1, name="my resource")


@post("/resources")
async def mirror_resource(data: Resource) -> Resource:
    return data

app = Litestar(route_handlers=[retrieve_resource, mirror_resource])

Run the app usint litestart run --reload.
Testing the app:


res = requests.get("http://localhost:8000/resources").json()
print(res)
# {'id': 1, 'name': 'my resource'}

res = requests.post("http://localhost:8000/resources", json={'id': 1, 'name': 'my resource'}).json()
print(res)
# {'id': 1, 'name': 'my resource'}

# With msgspec.Struct the post requests returns a 400.

# {'status_code': 400,
# 'detail': 'Validation failed for POST http://localhost:8000/resources',
# 'extra': [{'message': 'instance of Resource expected', 'key': 'data'}]}

Is this a bug, or did I something wrong?

strange parrot
#

i am not sure we already implemented this. @sand shale ?

cyan spoke
#

We have not, no

#

You can kinda work around this by using DTOs

#

But bare Structs are currently only supported as a return value

serene jungle
#

I´ll go with attrs than 🙂 and will also have a closer look into DTOs. Currently it seems to introduce a lot of overhead in simple apps and isn´t necessary in simple apps.

cyan spoke
serene jungle
#

I don´t use SQLALChemy. Most of my data lives in a data lake (minio or aws s3) as parquet files or json inside a request. But I definitely have to take a deeper look into DTOs.

sand shale
#

I'm hoping we get to the point where the structs are natively supported also - the msgspec signature model RFC PR would achieve this

#

I'll make a push to get that done this week

serene jungle