Replies: 2 comments
-
|
Hey @cwinters . Thank you for the suggestion. I've created the PR for that: #15499 |
Beta Was this translation helpful? Give feedback.
-
|
I would make this opt-in if FastAPI adds support for it. The current declared-type serialization behavior is an important safety default: if the response field is typed as For now, the explicit workaround you showed is the safest one: content = model.model_dump_json(polymorphic_serialization=True)
return Response(content=content, media_type='application/json')or use Pydantic's annotation-level tools when the polymorphic field is part of the public contract. If this becomes a FastAPI route option, I think it should probably be route-level or response-model-level rather than silently inferred everywhere from model config. That would keep the security boundary obvious in code review: @app.get('/...', response_model=OuterModel, polymorphic_serialization=True)The tests should cover nested models and lists, but also the sensitive-subclass-field case, because that is exactly the behavior difference between declared-type and actual-type serialization. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
First Check
Commit to Help
Example Code
Description
polymorphic_serialization=Trueto serialize a model with its actual type vs declared typepolymorphic_serializationoption pydantic/pydantic#12518@app.get(..., polymorphic_serialization=True)), or...Operating System
Linux, macOS
Operating System Details
No response
FastAPI Version
0.135.3
Pydantic Version
2.13.4
Python Version
3.11.14
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions