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

前端 未结 3 1445
执笔经年
执笔经年 2020-12-10 10:57

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

paths:
  /payloads:
    post:
      summary: create a pay         


        
3条回答
  •  攒了一身酷
    2020-12-10 11:32

    My way to go about this is to define an 'abstract' model which contains all the parameters. Then for each usecase, I will define a model that references the first one and indicates exactly what are the required fields.

    paths:
      /payloads:
        post:
          summary: create a payload
          ...
          parameters:
          - in: body
            name: payload
            description: New payload
            required: true
            schema:
              $ref: "#/definitions/NewPayload"
        put:
          summary: update a payload
          ...
          parameters:
          - in: body
            name: payload
            description: Updated existing payload
            required: true
            schema:
              $ref: "#/definitions/UpdatePayload"
    ...
    definitions:
      # This payload would be used with update requests and has no required params.
      NewPayload:
         allOf:
           - { $ref: '#definitions/PayloadProperties }
           - type: object
    
      # This payload would be used with update requests and require an id param.
      UpdatePayload:
         allOf:
           - { $ref: '#definitions/PayloadProperties }
           - type: object
             required: [id]
    
      PayloadProperties:
        properties:
          id:
            type: string
          someProperty:
            type: string
          ...
    

    I find this method rather clean as it doesn't require duplication, provides seperation of concerns and granularity.

提交回复
热议问题