Search code examples
c#asp.net-coreswaggerswagger-ui

Swagger same DateTime field Format different between Request and Response?


We have StartDate and endDate field in the Model with the datatype of DateTime. Swagger POST PayLoad json the default value of date is containing Z at the end. enter image description here

But the same field displaying in GET Request as response without Z. enter image description here

Could you please let me know any Swagger configuration need to be done from my end.


Solution

  • Could you please let me know any Swagger configuration need to be done from my end.

    This is unlikely a Swagger configuration issue.

    The date-time value returned in the response are not valid according to RFC3339, which is the standard for internet dates which OpenAPI implements. To be valid according to this standard, a time-zone component must be included in a date-time value. From RFC3339 section 5.6,

    full-time = partial-time time-offset

    The time-zone component is either a Z to indicate UTC time-zone, or it is an offset plus or minus some whole number of hours and minutes, for example +03:00.

    My guess would be that the OpenAPI specification which enables Swagger UI to generate the examples in your Swagger UI screengrabs contains a schema definition for the fields startDate and endDate in the response that doesn't restrict them to only allowing date-time formatted values.

    OpenAPI implements JsonSchema for type defintions, and according to the JsonSchema date-time format directive,

    Dates and times are represented in RFC 3339, section 5.6.

    So, if you modify the definition of these fields in the OpenAPI specification to properly reflect the fact that they are date-time restricted, then once you have also updated the examples within the specification, Swagger UI should display these values correctly.

    For example,

    components:
      schemas:
        MyResponseBody:
          type: object
          properties:
            startDate: 
              type: string
              format: date-time # <-- restricts values to internet date/time format
              example: 2024-02-16T17:28:51.595Z # <-- add the "Z" suffix to any examples
            endDate: 
              type: string
              format: date-time 
              example: 2024-02-16T17:28:51.595Z