-
-
Notifications
You must be signed in to change notification settings - Fork 7.5k
[BUG][python-fastapi] Generated server model to_dict() excludes readOnly fields, dropping valid response properties #23407
Description
OpenAPI Generator version
7.21.0
OpenAPI declaration file content or url
components:
schemas:
Process:
type: object
.....
completionProgress:
type: number
format: double
readOnly: true
minimum: 0
maximum: 1
example: 0.75
multipleOf: 0.0001
description: "Completion progress of the quiz (0 to 1). Computed by backend."
additionalProperties: falseWhat I expected
Since python-fastapi is a server generator, generated response serialization should not exclude readOnly properties. For OpenAPI, readOnly means the field may appear in responses and should not be sent in requests. So a server response serializer should keep fields like completionProgress.
Expected generated code shape:
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
_dict = self.model_dump(
by_alias=True,
exclude={
},
exclude_none=True,
)
return _dictWhat it returns
The generated server model excludes readOnly fields unconditionally in to_dict().
Generated code currently looks like this:
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
* OpenAPI `readOnly` fields are excluded.
"""
excluded_fields: Set[str] = set([
"completion_progress",
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dictAs a result, valid response-only fields silently disappear from server responses.
For example, if the server model instance has:
Process(
....
completion_progress=0.75,
)then to_dict() produces a payload without completion_progress, even though it is a valid response field.
python-fastapi is a server generator, so unconditionally excluding readOnly fields from to_dict() appears to conflict with the OpenAPI meaning of readOnly.
This also seems closely related to the broader request/response modeling problem discussed in #4190.
Suggested fix
For python-fastapi server generation, to_dict() should not exclude readOnly fields by default.
Possible approaches:
- Generate server
to_dict()without excludingreadOnlyfields. - Split request vs response serialization helpers (for example
to_request_dict()vsto_dict()/to_response_dict()). - Generate distinct request and response models/serialization paths for schemas using
readOnly/writeOnly.