Lessons learned from API client generation - 07 Nullable

Oct 1, 2022

Sixth pattern of our series, nullable types. This one will be harder to crack. I’ve concluded that marking scalar types as nullable for the purpose of API client generation is not a useful piece of information. While the property might not be nullable on the service itself, it might not be selected by the client, or filtered out for security reasons, and the client needs to convey that information to the application. This is why in Kiota we’ve made the opiniated choice of making all scalar types nullable when generating models, regardless of what’s in the API description.

Over time, there has been several different ways of describing that something can potentially be null with OpenAPI and JSON schema as you can see in the following example.

schema:
  type: object
  properties:
    foo:
      type: number    # < 3.0
      nullable: true
    bar:
      oneOf:          # >= 3.0
        - type: number
        - type: null
    baz:
      type: [number, null] # >= 3.1

Suggestions

I think part of the responsibility to fix the confusion here is to make sure that OpenAPI parsing libraries, implement version 3.1, as well as hide or mark as deprecated old properties (nullable) and always serialize/deserialize to the latest recommendation (third example in the previous snippet). This will ease up the work of migration tools, and for generators.

Additionally, linters could implement a rule warning people when using 3.1 or above and using oneOf for nullable instead of a type array.

Lastly, I think that JSON schema and/or OpenAPI should put together a “recommendations for generators” page which, in my opinion, should include the choice we’ve made with Kiota to always make scalar types nullable.


Last edited Apr 15, 2024 by Vincent Biret


Tags: