Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

swagger - How to make a field in a definition required for some operations and not others

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
      ...

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You would have to define the models separately.

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

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...