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

How to reuse swagger definition in definitions?

代码如下:

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?

替换那些重复的代码

您可以使用 allOf 编写定义,这是一个完整的示例,其中在 FindUID 和 FindUsername 中使用了结果:

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/(披露:我写了这个教程)