如何使用 swagger 在路径中定义可选参数 [英] How to define an optional parameter in path using swagger
问题描述
我的 REST Web 服务中有一个使用 GET 方法的函数,它有两个可选参数.
There is a function in my REST web service working with GET method and it has two optional parameters.
我尝试在 Swagger 中定义它,但在我将 required
设置为 false
后遇到错误,不是有效的参数定义.
I tried to define it in Swagger but I encountered an error, Not a valid parameter definition, after I set the required
as false
.
我发现如果我将 required
值设置为 true
错误就会消失.这是我的 Swagger 代码示例.
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
我没有在正文或查询中的参数中遇到这种情况.我认为这个问题只与路径中的参数有关.我也无法在 swagger 规范文件中找到任何解决方案.
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.
有没有其他方法可以在 Swagger 中定义可选参数,或者我的代码中是否有任何错误?
Is there any other way to define optional parameters in Swagger or do I have any mistake in my code?
任何帮助将不胜感激.
推荐答案
鉴于 OpenAPI/Swagger 规范必须要求 path 参数,您可以考虑添加 2 个单独的端点,路径如下:
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}
当提供 param2 时/get/{param1}/
当没有提供 param2 时
这篇关于如何使用 swagger 在路径中定义可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!