I’m creating an OpenAPI Description for an endpoint with a specific payload structure:
- One field is mandatory
- Two additional fields are optional
- Only ONE of the optional fields can be present at a time (mutually exclusive)
Here’s what I’ve tried:
openapi: 3.0.4
info:
title: My API
version: 1.0.0
paths:
/my-endpoint:
post:
requestBody:
required: true
content:
application/json:
schema:
type: object
required:
- mandatoryField
properties:
mandatoryField:
type: string
optionalFieldOne:
type: string
optionalFieldTwo:
type: string
I am stuck here.
Pritam Bagad is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
There’s a third variation of required
and oneOf
type: object
required:
- mandatoryField
properties:
mandatoryField:
type: string
optionalFieldOne:
type: string
optionalFieldTwo:
type: string
oneOf:
- required:
- optionalFieldOne
- required:
- optionalFieldTwo
The easiest approach is to use maxProperties: 2
and forbid extra properties via additionalProperties: false
. This ensures that only one of the optional properties can be provided at most.
type: object
required:
- mandatoryField
properties:
mandatoryField:
type: string
optionalFieldOne:
type: string
optionalFieldTwo:
type: string
maxProperties: 2
additionalProperties: false
Another way to define mutually exclusive properties is to forbid simultaneous presence of those properties by using not
+ required
(but schemas with not
are less readable imo).
type: object
required:
- mandatoryField
properties:
mandatoryField:
type: string
optionalFieldOne:
type: string
optionalFieldTwo:
type: string
# This means: if both optionalFieldOne and optionalFieldTwo are present
# then the schema is not valid
not:
required:
- optionalFieldOne
- optionalFieldTwo
1