如何在定义中重用swagger定义?

时间:2016-11-03 09:51:24

标签: swagger

以下代码:

definitions:
  Result:
    type: object
    properties:
      code:
        type: integer
        format: int32
      message:
        type: string
  FindUID:
    type: object
    properties:
      code:
        type: integer
        format: int32
      message:
        type: string
      data:
        type: object
        properties:
          uid:
            type: integer
            format: int64
  FindUsername:
    type: object
    properties:
      code:
        type: integer
        format: int32
      message:
        type: string
      data:
        type: object
        properties:
          username:
            type: string

如您所见,FindUIDFindUsername的第一部分与Result相同。如何使用Result替换这些重复的代码?

1 个答案:

答案 0 :(得分:5)

您可以使用allOf撰写定义,这是在FindUID和FindUsername中使用Result的完整示例:

swagger: '2.0'
info:
  description: Example API Description
  title: Example Title
  version: 1.0.0
paths: {}
definitions:
  Result:
    type: object
    properties:
      code:
        type: integer
        format: int32
      message:
        type: string
  FindUID:
    allOf:
      - $ref: "#/definitions/Result"
      - type: object
        properties:
          data:
            type: object
            properties:
              uid:
                type: integer
                format: int64
  FindUsername:
    allOf:
      - $ref: "#/definitions/Result"
      - type: object
        properties:
          data:
            type: object
            properties:
              username:
                type: string

有关此内容的更多信息:https://apihandyman.io/writing-openapi-swagger-specification-tutorial-part-4-advanced-data-modeling/(披露:我编写本教程)