Arpit
Arpit

Reputation: 112

how define both required and anyof properties in OpenAPI 3.0

I am creating an OpenAPI 3 spec for an api which has object for which some property are required and for some they are anyof. When i create the spec as below it throws an error, which i am unable to fix.

EnrollementRequest:
      type: object
      properties:
        consent:
          $ref: "#/components/schemas/ConsentEnum"
        cid:
          $ref: '#/components/schemas/CID'
        card:
          $ref: '#/components/schemas/Card'
        enrollmentDateTime :
          description: The date and time of enrollment with respective timezone
          format: date-time
          example: 2018-11-13T20:20:39+00:00
        campaign_code: 
          description: the campaign-code for which customer wants to enroll
          type: string
        offer_code:
          description: the offer-code for which customer wants to enroll
          type: string
        channelInfo:
          $ref: '#/components/schemas/Channel'
      required:
        - consent
        - cid
        - enrollmentDateTime
        - channelInfo
      anyOf:
        - campaign_code
        - offer_code       

Swagger editor gives an error as below -

Errors

Structural error at components.schemas.EnrollementRequest.anyOf.0
should be object
Jump to line ...
Structural error at components.schemas.EnrollementRequest.anyOf.1
should be object
Jump to line ...

Upon using the suggestion as below

  anyOf:
    - required: [campaign_code]
    - required: [offer_code]

the validation error went away but the swagger editor schema / model view is not showing any content as below -

enter image description here

Upvotes: 2

Views: 10184

Answers (1)

Mafor
Mafor

Reputation: 10681

Right, anyOf must be a list of objects. Try this:

      anyOf:
        - required: [campaign_code]
        - required: [offer_code] 

Alternativelly, to make it look better in the Swagger editor:

    EnrollementRequest:
      type: object
      properties:
        consent:
          $ref: "#/components/schemas/ConsentEnum"
        cid:
          $ref: '#/components/schemas/CID'
        card:
          $ref: '#/components/schemas/Card'
        enrollmentDateTime :
          description: The date and time of enrollment with respective timezone
          format: date-time
          example: 2018-11-13T20:20:39+00:00
        channelInfo:
          $ref: '#/components/schemas/Channel'
      required:
        - consent
        - cid
        - enrollmentDateTime
        - channelInfo
      anyOf:
        - properties:
            campaign_code: 
              description: the campaign-code for which customer wants to enroll
              type: string
          required: [campaign_code] 
        - properties: 
            offer_code:
              description: the offer-code for which customer wants to enroll
              type: string
          required: [offer_code] 

Upvotes: 5

Related Questions