Skip to content

[BUG] Patch operations reset fields to default if not specified #23650

@fennerm

Description

@fennerm

When using the Python generator, PATCH requests can reset fields to their default values even when the client did not explicitly set those fields. This happens specifically if a default value is specified in the PatchedModel spec. Even though we are defining this default, I don't think it matches user expectations for the value to be implicitly set in the patch request. Openapigenerator 5.4.0 did not exhibit this behavior

openapi-generator version

7.22.0

OpenAPI declaration file content or url

openapi: 3.0.3
info:
  title: Example API
  version: 1.0.0
paths:
  /users/{id}:
    patch:
      operationId: users_partial_update
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PatchedUser'
      responses:
        '200':
          description: Success
components:
  schemas:
    PatchedUser:
      type: object
      properties:
        name:
          type: string
          default: ""
        status:
          type: string
          default: "active"
        priority:
          type: integer
          default: 0

Generated SDK model:

class PatchedUser(BaseModel):
    """
    PatchedUser
    """ # noqa: E501
    name: Optional[StrictStr] = ''
    status: Optional[StrictStr] = 'active'
    priority: Optional[StrictInt] = 0
    __properties: ClassVar[List[str]] = ["name", "status", "priority"]
    model_config = ConfigDict(
        populate_by_name=True,
        validate_assignment=True,
        protected_namespaces=(),
    )
    def to_dict(self) -> Dict[str, Any]:
        """Return the dictionary representation of the model using alias."""
        excluded_fields: Set[str] = set([
        ])
        _dict = self.model_dump(
            by_alias=True,
            exclude=excluded_fields,
            exclude_none=True,  # <-- The problem: doesn't exclude unset fields with defaults
        )
        return _dict

Steps to reproduce

openapi-generator generate -i openapi-bug-report.yaml -g python -o ./bug-report-sdk --package-name bug_report_sdk

Related issues/PRs

Suggest a fix/enhancement

Maybe it would make sense to use exclude_unset=True instead of exclude_none=True when serializing Pydantic models for requests?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions