I have the following OpenAPI (Swagger) definition for a POST request with form data. How can I vary the required form parameters based on the value of the type parameter?
If type="email" only the email is required and if type="phone" only country and phone parameters are required.
/login:
post:
required:
- type
- password
responses:
200:
description: Successful response
schema:
$ref: '#/definitions/SomeResponse'
parameters:
- name: type
type: string
in: formData
enum: [email, phone]
- name: email
type: string
in: formData
- name: country
type: string
in: formData
- name: phone
type: string
in: formData
- name: password
type: string
Conditional dependencies in form data can be expressed in OpenAPI 3, but not in OpenAPI 2.0 (swagger: 2.0).
This example uses if..then, a new construct in OAS 3.1.
openapi: 3.1.0
...
paths:
/login:
post:
requestBody:
required: true
content:
application/x-www-form-urlencoded:
schema:
$ref: '#/components/schemas/LoginRequest'
responses:
'200':
description: Successful response
components:
schemas:
LoginRequest:
type: object
required:
- type
- password
properties:
type:
type: string
enum: [email, phone]
email:
type: string
country:
type: string
phone:
type: string
password:
type: string
# Conditional dependencies
allOf:
# If type="email", then the `email` field is required
- if:
properties:
type:
const: email
then:
required: [email]
# If type="phone", then the `country` and `phone` fields are required
- if:
properties:
type:
const: phone
then:
required: [country, phone]
In OAS 3.0, you can use the following oneOf construct to express these conditions.
openapi: 3.0.3
...
paths:
/login: ... # The path definition is the same as in the previous example
components:
schemas:
LoginRequest:
type: object
required:
- type
- password
properties:
type:
type: string
enum: [email, phone]
email:
type: string
country:
type: string
phone:
type: string
password:
type: string
# Conditional dependencies
oneOf:
# If type="email" ...
- properties:
type:
enum: [email]
# ... then the `email` field is required
required: [email]
# If type="phone" ...
- properties:
type:
enum: [phone]
# ...then the `country` and `phone` fields are required
required: [country, phone]
In OpenAPI 2.0, the most you can do is define the conditionally required parameters (email, country and phone in your example) as optional and mention the dependencies in the operation description and/or parameter descriptions.
swagger: '2.0'
...
paths:
/login:
post:
...
parameters:
- name: type
type: string
in: formData
enum: [email, phone]
required: true
- name: email
type: string
in: formData
description: Required if type=email
- name: country
type: string
in: formData
description: Required if type=phone
- name: phone
type: string
in: formData
description: Required if type=phone
- name: password
type: string
in: formData
required: true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With