OpenAPITools / OpenAPITools/openapi-generator

[BUG][python-fastapi] Generated server model `to_dict()` excludes `readOnly` fields, dropping valid response properties

Open
#23,407 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Java
Stars
26.8k
Forks
7.7k
PR merge metrics
PR metrics pending

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: false
What 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 _dict
What 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 _dict

As 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 excluding readOnly fields.
  • Split request vs response serialization helpers (for example to_request_dict() vs to_dict() / to_response_dict()).
  • Generate distinct request and response models/serialization paths for schemas using readOnly / writeOnly.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the python-fastapi model-generation entry point responsible for the generated to_dict() method, and compare its readOnly handling with the expected output shown here. Verify that completionProgress remains in server response serialization, then add or run a regression test showing that a populated readOnly field is preserved.

Written by the indexing model from the issue text.

Assessment

Tech stack
fastapi, openapi, python
Domain
api, backend, tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.