3

My API exposes some endpoints with DateTime? and others with DateTimeOffset?.

I want to generate an API Client using OpenApi-Generator, that will create client code for each endpoint, respecting the differences between the types.

OpenApi-Generator offers the option to useDateTimeOffset=true, which will generate the client using DateTimeOffset everywhere regardless of whether the API was exposing DateTime or DateTimeOffset. As such, I don't want to use that.

So to resolve the requirement without that, I'm attempting to create a Filter in which I will specify that in the case of DateTimeOffset? the generator should use the type DateTimeOffset and make it nullable.

This is the Filter:

public class FixDateTimeOffsetTypeSchemaFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema model, SchemaFilterContext context)
    {
        if (context.Type == typeof(DateTimeOffset?))
        {
            model.Format = "date-time-offset-nullable";
            model.Type = "DateTimeOffset"; 
            model.Nullable = true;
        }
    }
}

and this is an example of the output from that:

"/Api/MyApiEndpoint": {
  "get": {
    "tags": [
      "General"
    ],
    "operationId": "General_MyApiEndpoint",
    "parameters": [
      {
        "name": "startDatetime",
        "in": "query",
        "schema": {
          "type": "DateTimeOffset",
          "format": "date-time-offset-nullable",
          "nullable": true
        }
      },

When I run this and generate the client from that JSON, the the DateTimeOffset objects are never nullable. It doesn't seem to respect that instruction.

What do I need to change to make it work, so that when I specify DateTimeOffset should be nullable, it appears as nullable in the code?

DaveDev
  • 41,155
  • 72
  • 223
  • 385

1 Answers1

1

It looks like this is a known problem: https://github.com/OpenAPITools/openapi-generator/pull/3530

And here is the pull request that solves it: https://github.com/OpenAPITools/openapi-generator/pull/3530/commits/89fd5d70e9f15a5be9ffe26c2beddc07770043c0

Also check this link: https://jane.readthedocs.io/en/latest/tips/nullable.html

dc914337
  • 415
  • 4
  • 14
  • For 300 points I'd like a more comprehensive answer than just links – DaveDev Sep 01 '21 at 23:28
  • It is hard to answer something certain without knowing the open API generator version. If the version is <4.1.0 - updating it should resolve it. If updating is not possible - you can still patch it. Syntax also differs depending on the version. Which version are you using? – dc914337 Sep 02 '21 at 14:59