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

goo*_*nsu 3 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
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,第一部分FindUIDFindUsername是一样的Result.如何用这些重复的代码替换Result

Arn*_*ret 6

您可以使用以下组成定义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
Run Code Online (Sandbox Code Playgroud)

更多关于这一点:https://apihandyman.io/writing-openapi-swagger-specification-tutorial-part-4-advanced-data-modeling/(披露:我写了这个教程)