OpenAPITools / OpenAPITools/openapi-generator

[BUG] [Dart] Optional number properties aren't being parsed as null

Open
#21,114 2 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Issue: Bug
Dominant language
Java
Stars
26.8k
Forks
7.7k
PR merge metrics
PR metrics pending

Description

Bug Report Checklist
  • Have you provided a full/minimal spec to reproduce the issue?
  • Have you validated the input using an OpenAPI validator (example)?
  • Have you tested with the latest master to confirm the issue still exists?
  • Have you searched for related issues/PRs?
  • What's the actual output vs expected output?
  • [Optional] Sponsorship to speed up the bug fix or feature request (example)
Description

When a property with a number type is set on a component schema and isn't set as a required key, it causes a parsing error at runtime when that value isn't in the json or is null.

Specifically, the error is in the fromJson() method when num.parse() is called, which expects the value to be non-null.

Workaround: add "nullable": true onto the property in the spec, but ideally properties should be treated as optional by default since the OpenAPI 3.0 spec says that they are here.

openapi-generator version

Library version: ^6.1.0
Flutter version: 3.29.0

OpenAPI declaration file content or url
{
  "openapi": "3.0.0",
  "info": {
    "title": "Sample API",
    "version": "1.0.0"
  },
  "paths": {
    "/test": {
      "get": {
        "responses": {
          "200": {
            "description": "Success",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Foo"
                }}}}}}}},
  "components": {
    "schemas": {
      "Foo": {
        "type": "object",
        "properties": {
          "bar": {
            "type": "number"
          }}}}}}
Generation Details
java -jar openapi-generator-cli-7.12.0.jar generate -i openapi.json -g dart -o test-openapi
Steps to reproduce

Execute shell command written above, using the support files included above, then check the generated dart code in .\test-openapi\lib\model\foo.dart.

Should produce this:

...

class Foo {
  /// Returns a new [Foo] instance.
  Foo({
    this.bar,
  });

  ///
  /// Please note: This property should have been non-nullable! Since the specification file
  /// does not include a default value (using the "default:" property), however, the generated
  /// source code must fall back to having a nullable type.
  /// Consider adding a "default:" property in the specification file to hide this note.
  ///
  num? bar;

  ...

  /// Returns a new [Foo] instance and imports its values from
  /// [value] if it's a [Map], null otherwise.
  // ignore: prefer_constructors_over_static_methods
  static Foo? fromJson(dynamic value) {
    if (value is Map) {
      final json = value.cast<String, dynamic>();

      // Ensure that the map contains the required keys.
      // Note 1: the values aren't checked for validity beyond being non-null.
      // Note 2: this code is stripped in release mode!
      assert(() {
        requiredKeys.forEach((key) {
          assert(json.containsKey(key), 'Required key "Foo[$key]" is missing from JSON.');
          assert(json[key] != null, 'Required key "Foo[$key]" has a null value in JSON.');
        });
        return true;
      }());

      return Foo(
        bar: num.parse('${json[r'bar']}'), // <<<<<<<<<<<<<<<<<<<<<<<--- runtime error here
      );
    }
    return null;
  }

  ...
}
Related issues/PRs

https://github.com/gibahjoe/openapi-generator-dart/issues/181

Suggest a fix

Perhaps something like this:

return Foo(
  bar: json[r'bar'] == null ? null : num.parse('${json[r'bar']}'),
);

or

return Foo(
  bar: num.tryParse('${json[r'bar']}'),
);

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Run the Java OpenAPI Generator command and inspect test-openapi/lib/model/foo.dart, especially Foo.fromJson(). Reproduce the missing or null bar value with the supplied OpenAPI declaration; done means generated Dart parsing accepts the optional number without a runtime error while preserving required-key checks.

Written by the indexing model from the issue text.

Assessment

Tech stack
dart, openapi
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.