如何在 OpenAPI 3.0 的模式中使用 $ref?

How to use $ref within a schema in OpenAPI 3.0?

我想在 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 的正确语法是什么?

$ref 用于 而不是 type,而不是 type 的值。另请注意 : 之后的 space 以分隔 YAML 中的键和值。

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

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

其中一个 属性 名称似乎也有拼写错误 - 它在 GetQuestion 架构中是 get-questions(复数),但在 get-question(单数)中您的 JSON 示例。我猜应该是 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