Replies: 2 comments
-
Further testing proved that the builtin @router.get("/{item_id}", response=Item | list[Item])
async def get_item(request, item_id: int, similar: int | None = None):
if similar is None:
res = await fetch_item(item_id)
from ninja import NinjaAPI
api = NinjaAPI()
# this prints the correctly formatted camelCase JSON!
print(api.renderer.render(request, res, response_status=200))
return res
else:
return await fetch_similar_items(item_id, similar) |
Beta Was this translation helpful? Give feedback.
-
Found this in result = validated_object.model_dump(
by_alias=self.by_alias,
exclude_unset=self.exclude_unset,
exclude_defaults=self.exclude_defaults,
exclude_none=self.exclude_none,
**model_dump_kwargs,
)["response"]
return self.api.create_response(
request, result, temporal_response=temporal_response
) So we do have a I think it might be more elegant if we simply use methods on Pydantic model itself to dump data into json. It might save some lines of code, plus users will be able to customize serializing behavior inside the schema and use it everywhere, without having to pass arguments to each decorator. @vitalik Is this something worse implementing? |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I'm trying to build endpoints that uses snake_case on Python server side, and all responses sent to JavaScript client sides use camelCase. After some research, I found that this can be done with Pydantic aliases:
So I built my
Item
on top of the customizedBaseModel
.In testing, the printed json is in deed using camelCase, but the response sent to client side is still in snake_case. This is very confusing It seems like the in serializing models/schemas, the idiomatic methods like
model_dump_json
are not used.EDIT: I also tried extend from
ninja.Schema
, but the problem stays the same.Beta Was this translation helpful? Give feedback.
All reactions