There is a function in my REST web service working with GET method and it has two optional parameters.
I tried to define it in Swagger but I encountered an error, Not a valid parameter definition, after I set the required
as false
.
I found out that if I set the required
value as true
the error will be gone. Here is a sample of my Swagger code.
...
paths:
'/get/{param1}/{param2}':
get:
...
parameters:
- name: param1
in: path
description: 'description regarding param1'
required: false
type: string
- name: param2
in: path
description: 'description regarding param2'
required: false
type: string
I didn't experience this with parameters in body or the the ones in query. I think this problem is only related to parameters in path. I could not find any solution in swagger specification files either.
Is there any other way to define optional parameters in Swagger or do I have any mistake in my code?
Any help would be appreciated.
Try adding 2 endpoints for the same API. like
/get/{param1}/{param2}
and/get/{param1}/{param2}/{param3}
Your YAML fails because as it stated on the specification:
Source: http://swagger.io/specification/#parameterObject (Look in fixed fields table)
Given that path parameter must be required according to the OpenAPI/Swagger spec, you can consider adding 2 separate endpoints with the following paths:
/get/{param1}/{param2}
when param2 is provided/get/{param1}/
when param2 is not providedIt it likely blowing up because you cannot have a base uri parameter optional, only query string values (in the case of a url).
For example:
This should work:
This should not work
change your "in" property to be "query" instead of "path" and it should work.
Sad but fact there is no official support for optional parameters still in 2020 and in 3.* specification: https://github.com/OAI/OpenAPI-Specification/issues/93
You can only apply some workaround mentioned in other answers (describe several endpoints for every set of parameters; convert your API to work with query-parameters instead of path-parameters).
Personally I decided to just leave everything as is, just add a parameter
description
which clearly says "This parameter is OPTIONAL!". Should be clear enough for everyone who reads the API.