2

我正在尝试使用 Swagger 记录 REST API。来自我们 API 的简化 JSON 响应如下所示:

{ 
    "data": {
        "type": "person"
        "id": "1"
        "attributes": {
          "name": "Joe"
          "age": 32
          ...
        }
        "links": {
            ...
        }
    }
}

或者

{ 
    "data": {
        "type": "job"
        "id": "22"
        "attributes": {
          "name": "Manager"
          "location": "Somewhere"
          ...
        }
        "links": {
            ...
        }
    }
}

他们对成功 GET 的 Swagger 定义可能如下所示:

   '200':
      description: OK.
      schema:
        type: object
        properties:
          data:
            type: object
            properties:
              id:
                type: string
              type:
                type: string
              attributes:
                $ref: '#/definitions/person'

或者

   '200':
      description: OK.
      schema:
        type: object
        properties:
          data:
            type: object
            properties:
              id:
                type: string
              type:
                type: string
              attributes:
                $ref: '#/definitions/job'

在我们的 Swagger 文件中可能有很多这样的重复。是否可以定义这些响应以共享公共部分?即我不想输入或复制/粘贴这部分数十次:

   '200':
      description: OK.
      schema:
        type: object
        properties:
          data:
            type: object
            properties:
              id:
                type: string
              type:
                type: string

我看不出使用鉴别器字段或使用 $ref 将如何工作。

4

1 回答 1

3

你可以allOf用来做组合(结合discriminator你可以做继承,但它不是真正的功能)

allOf与模式或引用数组一起使用时,它将创建一个新定义,其中包含数组中所有定义的所有属性。

鉴于您希望您的一些定义共享idtype属性,它是这样做的:

swagger: '2.0'
info:
  version: 1.0.0
  title: API

paths: {}

definitions:
  SharedDefinition:
    properties:
      id:
        type: string
      type:
        type: string

  Person:
    allOf:
      - $ref: '#/definitions/SharedDefinition'
      - properties:
          firstname:
            type: string
          lastname:
            type: string

  JobSubDefinition:
    properties:
      name:
        type: string

  Job:
    allOf:
      - $ref: '#/definitions/SharedDefinition'
      - $ref: '#/definitions/JobSubDefinition'

在这个例子中:

  • Person = SharedDefinition + 内联定义
  • Job = SharedDefinition + JobSubDefinition

更多关于这个的

于 2016-05-16T14:59:53.333 回答