How to define an optional parameter in path using swagger

后端 未结 5 1916
名媛妹妹
名媛妹妹 2020-12-29 00:51

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, <

相关标签:
5条回答
  • 2020-12-29 01:21

    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.

    0 讨论(0)
  • 2020-12-29 01:23

    Try adding 2 endpoints for the same API. like

    /get/{param1}/{param2} and /get/{param1}/{param2}/{param3}

    0 讨论(0)
  • 2020-12-29 01:38

    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
    0 讨论(0)
  • 2020-12-29 01:39

    Your YAML fails because as it stated on the specification:

    Determines whether this parameter is mandatory. If the parameter is in "path", this property is required and its value MUST be true.

    Source: http://swagger.io/specification/#parameterObject (Look in fixed fields table)

    0 讨论(0)
  • 2020-12-29 01:45

    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.

    0 讨论(0)
提交回复
热议问题