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

Joseph Downing picture Joseph Downing · Jun 17, 2015 · Viewed 8.5k times · Source

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?

Answer

Ron picture Ron · Jun 17, 2015

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.