首页 > 解决方案 > 如何在 OpenAPI 3.0 的模式中使用 $ref?

问题描述

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

{
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

解决方案


$ref用于代替,而type不是作为 的值type。还要注意:YAML 中用于分隔键和值的空格。

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

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

其中一个属性名称似乎也有错字 - 它在模式中是get-questions(复数),但在您的 JSON 示例中是(单数)。我想应该是。GetQuestionget-questionget-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

推荐阅读