23

我正在尝试为一个时间间隔构建一个 Swagger 模型,使用一个简单的字符串来存储时间(我知道还有 datetime):

definitions:
  Time:
    type: string
    description: Time in 24 hour format "hh:mm".
  TimeInterval:
    type: object
    properties:
      lowerBound:
        $ref: "#/definitions/Time"
        description: Lower bound on the time interval.
        default: "00:00"
      upperBound:
        $ref: "#/definitions/Time"
        description: Upper bound on the time interval.
        default: "24:00"        

由于某种原因,生成的 HTML 不显示 lowerBound 和 upperBound “描述”,而只显示原始时间“描述”。这让我觉得我没有正确地做到这一点。

所以问题是如果使用模型作为类型实际上可以像我试图做的那样完成。

4

1 回答 1

24

TL;DR:$refOpenAPI 3.1 支持兄弟姐妹。在以前的 OpenAPI 版本中,旁边的任何关键字都会$ref被忽略。

开放API 3.1

迁移到 OpenAPI 3.1 后,您的定义将按预期工作。这个新版本与 JSON Schema 2020-12 完全兼容,它允许schemas$ref中的兄弟姐妹。

openapi: 3.1.0
...

components:
  schemas:
    Time:
      type: string
      description: Time in 24 hour format "hh:mm".

    TimeInterval:
      type: object
      properties:
        lowerBound:
          # ------- This will work in OAS 3.1 ------- #
          $ref: "#/components/schemas/Time"
          description: Lower bound on the time interval.
          default: "00:00"
        upperBound:
          # ------- This will work in OAS 3.1 ------- #
          $ref: "#/components/schemas/Time"
          description: Upper bound on the time interval.
          default: "24:00"  

在模式之外- 例如,在响应或参数中 - $refs 只允许同级summarydescription关键字。这些 $ref 旁边的任何其他关键字都将被忽略。

# openapi: 3.1.0

# This is supported
parameters:
  - $ref: '#/components/parameters/id'
    description: Entity ID

# This is NOT supported
parameters:
  - $ref: '#/components/parameters/id'
    required: true

OpenAPI 2.0 和 3.0.x

在这些版本中,$ref通过将自身及其所有同级元素替换为它所指向的定义来工作。这就是为什么

      lowerBound:
        $ref: "#/definitions/Time"
        description: Lower bound on the time interval.
        default: "00:00"

变成

      lowerBound:
        type: string
        description: Time in 24 hour format "hh:mm".

一种可能的解决方法是 wrap $refinto allOf- 这可用于将属性“添加”到 a$ref但不覆盖现有属性。

      lowerBound:
        allOf:
          - $ref: "#/definitions/Time"
        description: Lower bound on the time interval.
        default: "00:00"

另一种方法是使用$ref内联定义替换。

definitions:
  TimeInterval:
    type: object
    properties:
      lowerBound:
        type: string  # <------
        description: Lower bound on the time interval, using 24 hour format "hh:mm".
        default: "00:00"
      upperBound:
        type: string  # <------
        description: Upper bound on the time interval, using 24 hour format "hh:mm".
        default: "24:00"
于 2017-01-19T22:04:55.680 回答