system
1
Originally posted by gary002g on September 07, 2021
I need to define a request for a searching service in JSON.
Request can have either geographical coordinates (longitude and latitude) or postal code.
Either one must be present. If longitude is present, then latitude is required and vice versa.
If both are omitted, postal code must be present. If geo coordinates present, postal code is optional (will be ignored if present).
I am having trouble defining such request in swagger editor.
If someone can help me, I will appreciate it greatly.
We are using v.3.0.3 and the swagger file will be used to generate client code.
system
2
Originally posted by richie on September 08, 2021
Hey gary002g,
If i understand correctly, it depends on the version of OAS youre using. Swagger versions 1 and 2 dont support cross field validation.
OpenAPI (swagger version 3) does support cross field dependencies. You can use the “oneOf” attribute to do this.
Cheers,
Rich
system
3
Originally posted by gary002g on September 08, 2021
I have seen in the spec that OpenAPI does support oneOf and anyOf.
However, I need something similar to the following construct that exists in JSON schema:
“dependencies”: {
“postalCode”: [“countryCode”],
“longitude”: [“latitude”],
“latitude”: [“longitude”]
},
“anyOf”: [
{
“required”: [“longitude”, “latitude”]
},
{
“required”: [“postalCode”]
},
{
“required”: [“city”, “state”, “countryCode”]
}
]
I haven’t seen these dependencies in the spec.
I tried to do this:
“required”: [
“distance”,
“distanceUnits”,
“anyOf”: [
{“longitude”, “latitude”},
{“postalCode”, “countryCode”},
{“city”, “state”, “countryCode”}
]
]
but swagger editor gives me an error on anyOf construct.
system
4
Originally posted by HKosova on September 13, 2021
(Copying my answer from Stack Overflow)
To define oneOf/anyOf logic for request parameters, you would have to define all parameters as a single object-type parameter, as explained here.
parameters:
- in: query
name: params # This name will NOT appear in the request URL
# but will be used in generated client SDKs / server stubs
required: true
# serialize this object as ?key1=value1&key2=value2
style: form
explode: true
schema:
type: object
properties:
longitude: { ... }
latitude: { ... }
postalCode: { ... }
countryCode: { ... }
city: { ... }
state: { ... }
anyOf:
- required: [longitude, latitude]
- required: [postalCode, countryCode]
- required: [city, state, countryCode]
Note that OpenAPI 3.0 does not support the dependencies keyword of JSON Schema, but it’s supported in OpenAPI 3.1 (the latest version).
There’s also an existing feature request in the OpenAPI Specification repository to support dependencies between individual parameter definitions.