koxudaxi / datamodel-code-generator

Pydantic model and dataclasses.dataclass generator for easy conversion of JSON, OpenAPI, JSON Schema, and YAML data sources.
https://koxudaxi.github.io/datamodel-code-generator/
MIT License
2.74k stars 301 forks source link

`default` value in OpenAPI 3.1 is missing when schema is referenced and the type is `["string", "null"]` #2092

Open chezou opened 1 month ago

chezou commented 1 month ago

Describe the bug When the default value is set in a referenced schema in OpenAPI 3.1 and it has type: ["string", "null"], the default value of dataclass becomes None while the non-referenced property properly sets the default value as described in the OpenAPI.

To Reproduce

Example schema:

openapi: 3.1.0
info:
  title: AutoML Notebook Parameters
  version: 1.0.0
components:
  schemas:
    UserColumn:
      type: ["string", "null"]
      default: userid
    Params1:
      type: object
      properties:
        user_column:
          $ref: '#/components/schemas/UserColumn'
        user_column2:
          type: ["string", "null"]
          default: userid
        user_column3:
          $ref: '#/components/schemas/UserColumn'
          default: userid

Used commandline:

$ datamodel-codegen --input .openapi.yaml --output-model-type dataclasses.dataclass --output model.py

And I got the following model.py:

# generated by datamodel-codegen:
#   filename:  openapi.yaml
#   timestamp: 2024-09-24T03:02:05+00:00

from __future__ import annotations

from dataclasses import dataclass
from typing import Optional

UserColumn = Optional[str]

@dataclass
class Params1:
    user_column: Optional[UserColumn] = None
    user_column2: Optional[str] = 'userid'
    user_column3: Optional[UserColumn] = 'userid'

Expected behavior

The expected dataclass is as follows:

# generated by datamodel-codegen:
#   filename:  openapi.yaml
#   timestamp: 2024-09-24T03:02:05+00:00

from __future__ import annotations

from dataclasses import dataclass
from typing import Optional

UserColumn = Optional[str]

@dataclass
class Params1:
    user_column: Optional[UserColumn] = 'userid'  # Should not be None
    user_column2: Optional[str] = 'userid'
    user_column3: Optional[UserColumn] = 'userid'

Version:

rafalkrupinski commented 3 days ago

Are you sure the field value should be initialised to the default OpenAPI value?

The default value shouldn't be transferred, it's implied be the receiving side.