如何在 OpenAPI 3.0 的架构中使用 $ref?

Man*_*dha 5 openapi

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

{
get-question: {
  question-id:string
  }
}
Run Code Online (Sandbox Code Playgroud)

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

{
get-question: {
  question-id:string
  }
}
Run Code Online (Sandbox Code Playgroud)

但我在 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
Run Code Online (Sandbox Code Playgroud)

什么是正确的语法$ref

Hel*_*len 6

$ref使用代替type,不作为对值type。还要注意:在 YAML 中分隔键和值之后的空格。

        get-questions:
          $ref: '#/components/schemas/QuestionID'
Run Code Online (Sandbox Code Playgroud)

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

其中一个属性名称似乎也有错字 - 它get-questionsGetQuestion架构中是(复数)但是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
Run Code Online (Sandbox Code Playgroud)