How to require at least one of two parameters in OpenAPI?
Asked Answered
M

1

17

I'm using OpenAPI 3 and have two query parameters, at least one of which is required but it doesn't matter which.

I.e., as sudocode:

if parameter_1 OR parameter_2:
    do stuff
else:
    error

Is this possible in OpenAPI 3? There's no mention of it in the spec as far as I can see, or the JSON Schema spec either.

Moppet answered 14/12, 2018 at 15:11 Comment(3)
Do you mean parameters (e.g. query/header params) or model/schema properties?Consumptive
Related: How to define mutually exclusive query parameters in Swagger (OpenAPI)?Consumptive
@Consumptive - Query parameters. Your answer in that question (https://mcmap.net/q/243096/-how-to-define-mutually-exclusive-query-parameters-in-swagger-openapi) does indeed answer my question. Alas it didn't come up in my search. Thanks!Moppet
C
16

This scenario is very similar to mutually exclusive parameters. Basically, you can use an object-type parameter where parameter_1 and parameter_2 are the object properties; such object will be serialized as ?parameter_1=value1&parameter_2=value2. The "at least one of" constraint can be represented using minProperties or anyOf.

openapi: 3.0.2
...
paths:
  /foo:
    get:
      parameters:
        - in: query
          name: param
          required: true
          schema:
            type: object
            properties:
              parameter_1:
                type: string
              parameter_2:
                type: string
            additionalProperties: false

            # Option 1
            minProperties: 1

            # Option 2
            # anyOf:
            #  - required: [parameter_1]
            #  - required: [parameter_2]

There's also an existing feature request to support interdependencies between individual parameters in the parameters list:
https://github.com/OAI/OpenAPI-Specification/issues/256

Consumptive answered 18/12, 2018 at 9:52 Comment(4)
This did not work for me. The Kotlin OpenAPI generator (v6.6.0) will give me: fun foo(@NotNull @Valid `param`: FooParamParameter), which even doesn't compile :(Lovelovebird
It's a tooling issue. Open a bug with OpenAPI Generator: github.com/OpenAPITools/openapi-generator/issuesConsumptive
When I put this into the Swagger Editor and go to try it, despite it being in:query it tries to tell me that parameters are a JSON object, doesn't mention that only one must be specified, and doesn't display the description of the individual parameters.Dermatologist
This solution produces an error for me: {"message": "Missing property.", "path": "/param"}Astrophysics

© 2022 - 2024 — McMap. All rights reserved.