What is the correct way to declare a date in an OpenAPI / Swagger-file?

后端 未结 3 1251
盖世英雄少女心
盖世英雄少女心 2020-12-15 15:31

What is the correct way to declare a date in a swagger-file object? I would think it is:

  startDate:
    type: string
    description: Start date
    exampl         


        
相关标签:
3条回答
  • 2020-12-15 16:14

    pattern should be a regular expression. This is stated in the OpenAPI Specification.

    pattern (This string SHOULD be a valid regular expression, according to the ECMA 262 regular expression dialect)

    This is because OpenAPI objects are based off the JSON Schema specification.

    OpenAPI 2.0: This object is based on the JSON Schema Specification Draft 4 and uses a predefined subset of it.

    OpenAPI 3.0: This object is an extended subset of the JSON Schema Specification Wright Draft 00.

    If a web service exposes a date or a date-time that doesn't conform to the Internet Date/Time Format described in RFC3339, then date and date-time are not valid values for the format field. The property must be defined as having a type equal to string without using format. Instead, pattern can be used to give a regular expression that defines the date or date-time pattern. This allows a client tool to automatically parse the date or date-time.

    I also recommend putting the format in the description field so human consumers can read it more easily.

    0 讨论(0)
  • 2020-12-15 16:15

    The OpenAPI Specification says that you must use:

    type: string format: date # or date-time

    The patterns supported are defined in RFC 3339, section 5.6 (effectively ISO 8601) and examples are provided in section 5.8. So for date values should look like "2018-03-20" and for date-time, "2018-03-20T09:12:28Z". As such, when using date or date-time, the pattern is unnecessary and in fact, should be omitted.

    If you need to support dates/times formatted in a way that differs to RFC 3339, you are not allowed to specify your parameter as format: date or format: date-time. Instead, you should specify format: string with an appropriate pattern.

    Finally, note that a pattern of "YYYY-MM-DD" is invalid according to the specification: pattern must be a regular expression, not a placeholder or format string.

    If you are violating any of the above rules to work around bugs in tools that generate UIs from OpenAPI specifications, you should strongly consider raising these bugs with that tool, rather than generating an invalid OpenAPI spec to work around this.

    0 讨论(0)
  • 2020-12-15 16:30

    A correct example of declaring date in an Open API swagger file:

        properties:
          releaseDate:
            type: date
            pattern: /([0-9]{4})-(?:[0-9]{2})-([0-9]{2})/
            example: "2019-05-17"
    
    0 讨论(0)
提交回复
热议问题