【问题标题】:How to use $ref within a schema in OpenAPI 3.0?如何在 OpenAPI 3.0 的模式中使用 $ref?
【发布时间】:2018-11-26 06:49:16
【问题描述】:

我想在 OpenAPI 3.0 API 定义中将以下 JSON 表示为 schema

{
get-question: {
  question-id:string
  }
}

到目前为止,我已经写了:

components:
  schemas:
  #schema of a question-id
    QuestionID:   #{question-id: string}
      properties:
        question-id:
          type: string
      required:
        - question-id

  #schema of a get-question request which contains a question id      
    GetQuestion: #{get-question: {question-id:string}}
      properties:
        get-questions:
          type: $ref:'#/components/schemas/QuestionID'
      required:
        - get-questions

但我在 Swagger 编辑器中收到这些错误:

Schema error at components.schemas['GetQuestion']
should have required property '$ref'
missingProperty: $ref
Jump to line 79
Schema error at components.schemas['GetQuestion']
should match exactly one schema in oneOf
Jump to line 79
Schema error at components.schemas['GetQuestion'].properties['get-questions']
should have required property '$ref'
missingProperty: $ref
Jump to line 81
Schema error at components.schemas['GetQuestion'].properties['get-questions']
should match exactly one schema in oneOf
Jump to line 81
Schema error at components.schemas['GetQuestion'].properties['get-questions'].type
should be equal to one of the allowed values
allowedValues: array, boolean, integer, number, object, string
Jump to line 82

$ref 的正确语法是什么?

【问题讨论】:

标签: openapi


【解决方案1】:

$ref 被使用而不是 type,而不是type 的值。还要注意: 后面的空格,用于分隔 YAML 中的键和值。

        get-questions:
          $ref: '#/components/schemas/QuestionID'

您还需要将type: object 添加到您的QuestionIDGetQuestion 架构中,以表明它们是对象;仅properties 关键字是不够的。

其中一个属性名称似乎也有拼写错误 - 它在 GetQuestion 模式中是 get-questions(复数),但在您的 JSON 示例中是 get-question(单数)。我想应该是get-question

完整示例:

components:
  schemas:
    # schema of a question-id
    QuestionID:      # {question-id: string}
      type: object   # <-----
      properties:
        question-id:
          type: string
      required:
        - question-id

    #schema of a get-question request which contains a question id      
    GetQuestion:     # {get-question: {question-id:string}}
      type: object   # <-----
      properties:
        get-question:
          $ref: '#/components/schemas/QuestionID'   # <-----
      required:
        - get-questions

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-21
    • 2020-05-09
    • 1970-01-01
    • 2020-08-30
    • 2021-11-23
    • 1970-01-01
    相关资源
    最近更新 更多