如何在定义中创建某些操作而不是其他操作所需的字段 [英] How to make a field in a definition required for some operations and not others

查看:10
本文介绍了如何在定义中创建某些操作而不是其他操作所需的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 yaml 编写我的招摇定义.假设我有一个看起来像这样的定义.

I'm writing my swagger definition in yaml. Say I have a definition that looks something like this.

paths:
  /payloads:
    post:
      summary: create a payload
      ...
      parameters:
      - in: body
        name: payload
        description: New payload
        required: true
        schema:
          $ref: "#/definitions/payload"
    put:
      summary: update a payload
      ...
      parameters:
      - in: body
        name: payload
        description: Updated existing payload
        required: true
        schema:
          $ref: "#/definitions/payload"
...
definitions:
  payload:
    properties:
      id:
        type: string
      someProperty:
        type: string
      ...

有没有一种方法可以表明负载的 id 属性对于 PUT 操作是必需的,并且对于 POST 操作是可选的(或根本不应该出现)?

Is there a way that I can indicate that the id property of a payload is required for the PUT operation and is optional (or should not appear at all) for the POST operation?

推荐答案

你必须单独定义模型.

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

However, you have options for the cases of exclusion and difference.

如果您要排除,这是最简单的情况,请创建一个具有排除属性的模型,例如 ModelA.然后将 ModelB 定义为 ModelA 加上附加属性:

If you're looking to exclude, which is the easy case, create a model of with the excluded property, say ModelA. Then define ModelB as ModelA plus the additional property:

ModelB:
  allOf:
    - $ref: "#/definitions/ModelA"
    - type: object
      properties:
        id:
          type: string

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

If you're looking to define the difference, follow the same method above, and exclude the id from ModelA. Then define ModelB and ModelC as extending ModelA and add the id property to them, each with its own restrictions. Mind you, JSON Schema can allow you to follow the original example above for some cases to "override" a definition. However, since it is not really overriding, and one needs to understand the concepts of JSON Schema better to not make simple mistakes, I'd recommend going this path for now.

这篇关于如何在定义中创建某些操作而不是其他操作所需的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆