Skip to content

Number schemas with format hint are generated as object when type property is missing #5323

@rm-code

Description

@rm-code

Description

When generating C# types from OpenAPI schemas produced by Microsoft.AspNetCore.OpenApi, numerical properties that include format: "int32", format: "int64", etc. are being generated as object instead of int or long. This occurs when the schema includes a pattern validation and doesn't include a type.

Current Behavior

OpenAPI 3.0.4 Schema Example

Note how this omits an actual type:

          "temperatureF": {
            "pattern": "^-?(?:0|[1-9]\\d*)$",
            "format": "int32"
          },
          "temperatureD": {
            "pattern": "^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$",
            "format": "double"
          },
          "temperatureL": {
            "pattern": "^-?(?:0|[1-9]\\d*)$",
            "format": "int64"
          },

Generated C# code:

 public object TemperatureF { get; set; }
 public object TemperatureD { get; set; }
 public object TemperatureL { get; set; }

Expected Behavior

When a schema has a numerical format hint such as format: "int32", NSwag should generate the property as the appropriate number type.

Expected C# code:

public int TemperatureC { get; set; }
public double TemperatureD { get; set; }
public long TemperatureL { get; set; }

Steps to Reproduce

  1. Generate an OpenAPI spec using Microsoft.AspNetCore.OpenApi and target Microsoft.OpenApi.OpenApiSpecVersion.OpenApi3_0
  2. The spec will contain integer schemas like those shown above
  3. Use NSwag to generate C# types from this spec
  4. Integer properties are generated as object instead of int/long

Additional Information

The format keyword provides a strong hint about the intended data type and as far as I understand the 3.0.4 schema is technically correct albeit ambiguous. This issue affects code generators that depend on NSwag, including Refitter and potentially others.

OpenAPI 3.1.1 Schema Example

When targeting OpenApi 3.1.1, the generated schema now has been expanded to an array that includes both integer and string types.

{
  "temperatureC": {
    "pattern": "^-?(?:0|[1-9]\\d*)$",
    "type": [
      "integer",
      "string"
    ],
    "format": "int32"
  }
}

This already generates proper "int" properties with the current Nswag toolchain.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions