ThomasThiebaud
ThomasThiebaud

Reputation: 11999

How to require a field depending on the http method ?

I am trying to write a JSON API using swagger and I'm facing some problem because some fields are required or not depending on the method used.

Here are a line from the update specs

The resource object MUST contain type and id members.

and here one from the create specs

The resource object MUST contain at least a type member.

So currently I have

Customer: 
    title: Customer
    type: object
    required: ["id", "type"]
    properties:
      id:
        type: string
      type:
        type: string
      attributes:
        type: object
        properties:
          name:
            type: string
          address: 
            type: string

What I would lke to do is having required: ["id", "type"] for patch method but only required: ["type"] for post method. Is it possible to do it without redefining another Customer ?

Upvotes: 4

Views: 238

Answers (1)

DevDot
DevDot

Reputation: 61

You can achieve that using the below method:

  Customer: 
    title: Customer
    type: object
    required:
      - type
    properties:
      id:
        type: string
      type:
        type: string
      attributes:
        type: object
        properties:
          name:
            type: string
          address: 
            type: string
  Customer_patch: 
    type: object
    required:
      - id
    allOf:
      - $ref: '#/definitions/Customer'

You have to redefine Another Customer to put the additional required fields but you can reuse the actual Customer definition object.

Upvotes: 4

Related Questions