如何重用swagger定义并删除其中的一些参数?

wob*_*ano 10 api yaml swagger swagger-2.0 openapi

这是我的代码:

definitions:
  User:
    type: object
    properties:
      id:
        type: integer
      username:
        type: string
      first_name:
        type: string
      last_name:
        type: string
      password:
        type: string
      created_at:
        type: string
        format: date-time
      updated_at:
        type: string
        format: date-time
    required:
      - username
      - first_name
      - last_name
      - password

/api/users:
  post:
    description: Add a new user
    operationId: store
    parameters:
      - name: user
        description: User object
        in: body
        required: true
        type: string
        schema:
          $ref: '#/definitions/User'
    produces:
      - application/json
    responses:
      "200":
        description: Success
        properties:
          success:
            type: boolean
          data:
            $ref: '#/definitions/User'
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,在下面的帖子键中,/api/users我使用User定义作为我的架构。

我想减少我的代码,所以我重用该User定义作为我的模式。这里的问题是我不需要id,created_atupdated_at字段。

有没有办法只继承除提到的字段之外的某些字段?另外,我希望有一些建议可以让它变得更好,因为我正在努力学习招摇。谢谢。

小智 11

正如对类似问题的回答中所解释的:

您必须单独定义模型。

但是,您可以选择排除和差异的情况。

如果您想要排除(这是简单的情况),请创建一个具有排除属性的模型,例如 ModelA。然后定义ModelBModelA加上附加属性:

ModelB:
  allOf:
    - $ref: "#/definitions/ModelA"
    - type: object
      properties:
        id:
          type: string
Run Code Online (Sandbox Code Playgroud)

如果您想要定义差异,请遵循上面相同的方法,并从 中排除 id ModelA。然后将ModelBand定义ModelC 为扩展ModelA并向其添加 id 属性,每个属性都有自己的限制。请注意,JSON Schema 可以让您在某些情况下遵循上面的原始示例来“覆盖”定义。然而,由于它并不是真正重要的,并且需要更好地理解 JSON Schema 的概念以免犯简单的错误,所以我建议现在走这条路。