datamodel-code-generator icon indicating copy to clipboard operation
datamodel-code-generator copied to clipboard

Invalid RootModel generated when using additionalProperties on reference schema

Open joao-de-oliveira opened this issue 1 year ago • 0 comments

Describe the bug Generating pydantic_v2.BaseModel from jsonschema with a reference schema in another file alongside a "additionalProperties": false, creates an invalid Pydantic object.

To Reproduce

Example schema 1:

{
  "$schema": "http://json-schema.org/draft-07/schema",
  "components": {
    "schemas": {
      "metadata": {
        "additionalProperties": false,
        "properties": {
          "user": {
            "$ref": "#/components/schemas/user"
          }
        },
        "title": "Metadata schema",
        "type": "object"
      },
      "user": {
        "properties": {
          "name": {
            "description": "User full name",
            "example": "John Doe",
            "title": "Name of last person to edit file",
            "type": "string"
          }
        },
        "type": "object"
      }
    }
  }
}

Example schema 2:

{
  "$ref": "#/components/schemas/model",
  "$schema": "http://json-schema.org/draft-07/schema",
  "components": {
    "schemas": {
      "model": {
        "additionalProperties": false,
        "properties": {
          "metadata": {
            "$ref": "./common.json#/components/schemas/metadata"
          }
        },
        "type": "object"
      }
    }
  }
}

Used commandline:

$ datamodel-codegen --input src --input-file-type jsonschema --output output --output-model-type pydantic_v2.BaseModel --strict-types bool --use-double-quotes --use-standard-collections --use-union-operator

For reference, both files were placed in a directory named src and an output folder named output was also created.

Expected behavior The generated Python code contains:

class Model(RootModel[Any]):
    model_config = ConfigDict(
        extra="forbid",
    )
    root: Any

Whereas I expected:

class Model(RootModel[Any]):
    root: Any

In the generated file for Example 1. Removing the "additionalProperties": false, from Example 2 solves this though I'm not sure if this is intended behaviour as I don't see why it would be incorrect to define it that way.

Version:

  • OS: Linux Mint 22
  • Python version: 3.12.2
  • datamodel-code-generator version: 0.26.1

joao-de-oliveira avatar Oct 09 '24 22:10 joao-de-oliveira