Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define an optional parameter in path using swagger

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.

like image 364
Hedeshy Avatar asked Jan 26 '16 10:01

Hedeshy


People also ask

How do you specify optional parameters in Swagger?

You can use the default key to specify the default value for an optional parameter. The default value is the one that the server uses if the client does not supply the parameter value in the request. The value type must be the same as the parameter's data type.

How do you specify a path parameter in Swagger?

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 provided.

Can a path parameter be optional?

Hello, like described here (swagger-api/swagger-ui#380), path parameters are required and can't be optional.


2 Answers

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 provided
like image 118
William Cheng Avatar answered Oct 19 '22 05:10

William Cheng


It 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:

  • GET /products/{id}/pricing?foo=bar
  • ** If foo is optional then your IN parameter needs to be "query" not "path"
  • ** If {id} is optional then something is wrong. {id} can't be optional because it is contained within the base uri.

This should work:

{
"in":"query",
"required":false
}

This should not work

{
"in":"path",
"required":false
}

change your "in" property to be "query" instead of "path" and it should work.

like image 26
Jerrod Horton Avatar answered Oct 19 '22 07:10

Jerrod Horton