Skip to content

Modeling Decimal types as json-schema results in ambiguous typing #710

@bruno-f-cruz

Description

@bruno-f-cruz

Describe the bug
The json model builder for Decimal types results in the following signature:

"anyOf": [
            {
              "type": "number"
            },
            {
              "type": "string"
            }
          ],

This was a change from pydantic v1 that allows decimal numbers to be encoded as strings in order to preserve their numeric precision. (see details here).

Unfortunately, Pydantic goes a bit rogue and comes up with their own standard (at least I couldn't find anything in json-schema nor OpenApi??) of what a Decimal means by choosing a AnyOf[str | number] and solving the deserialization with custom logic (see source here).

This is unfortunate since the union is not discriminated, and thus makes it impossible to know what the type should resolve as.

Other users have also raised this issue. See this discussion for more details

Describe the solution you'd like
It would be nice to change the model class and force decimals to either always be strings or numbers. This can be done in two ways:

  1. Set the property of the model_json() method to Serialize instead of the default Validate
  2. Override the decimal_schema method in the implementation mentioned above and create our own custom model builder.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions