Repository navigation
🐛 Fix response model serialization options for SSE event data - #15708
k-shimura7617 wants to merge 3 commits into
Conversation
avinashkamat48
left a comment
There was a problem hiding this comment.
This applies the response-model serialization options only when ServerSentEvent.data is a Pydantic model with model_dump_json. The fallback branch still calls jsonable_encoder(item.data) without include, exclude, by_alias, or the exclude flags, so dicts/dataclasses/lists of models sent as event data will continue ignoring the route's response serialization options. Please either pass the same options through jsonable_encoder in the fallback path or add a test that documents the limitation.
|
Good catch, thanks. I updated the fallback Ran the focused SSE tests, related response serialization tests, |
YuriiMotov
left a comment
There was a problem hiding this comment.
For response_model_*** parameters to work we need to specify response model.
There are 2 ways to implement SSE endpoint:
- by declaring function return type as
-> AsyncIterable[Item]andyielding data asyield Item(...)oryield {...}- see docs. Response model in this case isItem - by declaring function return type as
-> AsyncIterable[ServerSentEvent]andyielding data asyield ServerSentEvent(data=Item(...))oryield ServerSentEvent(data={...})- see docs. Response model in this case isServerSentEvent.
If we use first approach (with AsyncIterable[Item] as return type annotation), then everything works on master, no fix needed.
See test in the details
from collections.abc import AsyncIterable
from fastapi import FastAPI
from fastapi.responses import EventSourceResponse
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
class Item(BaseModel):
name: str = Field(serialization_alias="itemName")
p1: str = "default"
p2: int | None
p3: int = 42
p4: str
app = FastAPI()
@app.get(
"/items/response_model-parameters-dict",
response_class=EventSourceResponse,
response_model_exclude_defaults=True,
response_model_exclude_none=True,
response_model_exclude_unset=True,
response_model_exclude={"p4"},
)
async def events_dict() -> AsyncIterable[Item]:
yield {"name": "Item 1", "p1": "default", "p2": None, "p4": "private"}
def test_events_dict() -> None:
response = TestClient(app).get("/items/response_model-parameters-dict")
assert response.text == 'data: {"itemName":"Item 1"}\n\n'The issue is only with the second approach.
But when we use second approach to declare endpoint, it's currently not possible to specify the schema for data field. Response model is ServerSentEvent that declares data as Any. And in openapi schema it's string.
So, not only response_model_*** parameters don't work - response model documentation and validation doesn't work when we use second approach.
So, I think we should start from raising this question first. And, when we have the ability to specify schema for data field, it will likely just work out of the box (as it works for the first approach described above).
So, let's close this for now and return to it later if we realize that resolving the bigger issue doesn't solve the issue with response_model_*** parameters
Pull Request
🐛 Fix response model serialization options for SSE event data
Discussion: #15703
Description
This fixes the
ServerSentEvent(data=...)serialization path for Pydantic models.Previously, this path called
model_dump_json()without forwarding the route's response model serialization options. Because of that, models used as SSE event data could ignore options such asresponse_model_by_alias,response_model_include,response_model_exclude,response_model_exclude_none,response_model_exclude_unset, andresponse_model_exclude_defaults.This now passes those options to
model_dump_json(), matching the behavior used by regular streamed response items.I added regression tests for serialization aliases,
response_model_by_alias=False,response_model_include,response_model_exclude,response_model_exclude_none,response_model_exclude_unset, andresponse_model_exclude_defaults.I ran locally:
AI Disclaimer
I used Codex as a coding assistant while preparing this PR.
After identifying the missing
by_aliashandling and confirming it in the discussion, I used Codex to inspect the sameServerSentEvent(data=...)serialization path for other response model serialization options.Codex helped me check for similar missing options, draft the focused regression tests, run local checks, and prepare this PR description. I reviewed the code changes, the test coverage, and the command results before opening the PR.
AI transcript
The code-related AI assistance was:
User:
I identified that
ServerSentEvent(data=...)does not respectby_aliaswhenthe data is a Pydantic model, and confirmed it in the discussion. Before opening
a PR, check whether the same path misses any other response model serialization
options.
Codex:
I will inspect the SSE serialization path and compare it with the regular
streamed response model serialization path.
In
fastapi/routing.py, plain streamed items use:But
ServerSentEvent(data=...)with a Pydantic model calls:So the same path is not only missing
by_alias; it is also missing the route'sinclude,exclude,exclude_unset,exclude_defaults, andexclude_noneserialization options.
User:
Update the fix so it handles the missing response model serialization options,
and add regression tests for the changed behavior.
Codex:
I updated the
model_dump_json()call to pass the route serialization options:I also added focused SSE regression tests for:
response_model_by_alias=Falseresponse_model_includeresponse_model_excluderesponse_model_exclude_noneresponse_model_exclude_unsetresponse_model_exclude_defaultsUser:
Run the focused checks.
Codex:
The focused checks passed:
Checklist