I'm looking for an elegant way to define an api that can consume JSON data as well as form data. The following snippet works, but it's not elegant and requires all kind of ugly code in the backend. Is there a better way to define this?
What works right now:
paths:
/pets:
post:
consumes:
- application/x-www-form-urlencoded
- application/json
parameters:
- name: nameFormData
in: formData
description: Updated name of the pet
required: false
type: string
- name: nameJSON
in: body
description: Updated name of the pet
required: false
type: string
Basic idea of how I'd like it to work:
paths:
/pets:
post:
consumes:
- application/x-www-form-urlencoded
- application/json
parameters:
- name: name
in:
- formData
- body
description: Updated name of the pet
required: true
type: string
But this doesn't work because the in
value must be a string, not an array.
Any good ideas?
OpenAPI 2.0
In OpenAPI 2.0, there's no way to describe that. Form and body parameters are mutually exclusive, so an operation can have either form data OR JSON body but not both. A possible workaround is to have two separate endpoints - one for form data and another one for JSON - if that is acceptable in your scenario.
OpenAPI 3.0
Your scenario can be described using OpenAPI 3.0. The
requestBody.content.<media-type>
keyword is used to define various media types accepted by the operation, such asapplication/json
andapplication/x-www-form-urlencoded
, and their schemas. Media types can have the same schema or different schemas.Further info: