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

时间:2018-11-26 06:49:17

标签: openapi

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

1 个答案:

答案 0 :(得分:2)

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

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

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

其中一个属性名称似乎也有错字-在get-questions模式中为GetQuestion(复数),在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