Repository navigation
ServerSentEvent data ignores Pydantic serialization_alias #15703
Replies: 6 comments 1 reply
|
The Until that's handled on the yield ServerSentEvent(raw_data=Item(name="Portal Gun").model_dump_json(by_alias=True))Don't route the JSON string through This looks worth filing as a bug: |
|
@kagami-tsukimura, this seems to be a real issue. We should probably also think what other similar flags are missing. Would be nice to address all of them in one PR (if any) |
|
I opened a PR for this: #15708 I also checked the same |
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 opened a PR for this: #15708
First Check
Commit to Help
Example Code
Description
I think I found a small inconsistency in how SSE payloads are serialized.
When a Pydantic model is yielded directly from an
EventSourceResponseendpoint, FastAPI serializes it using the external field names by default. That matches normal FastAPI responses and respectsserialization_alias.But when the same model is wrapped in
ServerSentEvent(data=...), the payload is serialized with the Python field name instead.In the example above, I expected the SSE payload to use
itemName, because the model defines:Actual output:
Expected output:
This matters because
serialization_aliasis often part of the API contract. For example, an API might expose camelCase fields to clients while using snake_case internally. If regular responses and direct SSE model yields use the alias, butServerSentEvent(data=...)does not, clients have to handle two different shapes for the same model.I checked the implementation and this seems to come from the SSE serialization path calling:
without passing
by_alias.A small fix would be to pass the existing FastAPI setting:
That would keep the default behavior aligned with normal FastAPI responses, while still respecting
response_model_by_alias=False.I searched existing issues, PRs, and discussions for
ServerSentEvent serialization_alias,EventSourceResponse serialization_alias,SSE response_model_by_alias, and related terms, but I did not find this exact case.Would a focused PR with regression tests for this behavior be welcome?
Operating System
Linux
Operating System Details
Ubuntu / local development environment
FastAPI Version
0.136.3
Pydantic Version
2.13.4
Python Version
Python 3.11.14
Additional Context
I have a local regression test and a small fix.
The regression test checks both cases:
serialization_aliasresponse_model_by_alias=Falsekeeps the Python field nameLocal verification:
Both pass locally.
I have not opened a PR yet, following the contributing guidance to start with a Discussion first.
All reactions