Flask-Smorest的Swagger-UI GET参数描述自定义问题
在Flask-Smorest的Swagger-UI中添加自定义参数描述文本
方法1:直接在视图函数的文档字符串中补充信息
Flask-Smorest会将视图函数的docstring作为Swagger-UI对应接口的描述内容,你可以直接在其中添加包含参数可选值、默认值的自定义文本,还能用Markdown语法格式化:
@ads_api.route('/test/<parameter>') class test(MethodView): @ads_api.response(200, TestResponseSchema) def get(self, parameter): """ testing 自定义参数说明: - 路径参数 `parameter`:可选有效值为 **ex1、ex2、ex3**,该参数为必填项,无默认值 """ print(parameter) if parameter in ['ex1','ex2', 'ex3']: response = {'status':'parameter exists'} return response else: abort(404, message='not found')
方法2:结合Marshmallow Schema定义参数(适用于查询/请求体参数)
如果是查询参数或请求体参数,推荐通过Marshmallow Schema定义时添加description和missing(默认值)字段,Swagger-UI会自动同步这些信息,同时你仍可以在docstring中补充自定义描述:
- 先定义查询参数的Schema:
class TestQuerySchema(Schema): optional_param = fields.Str( missing="default_val", description="可选查询参数,默认值为 default_val" )
- 在视图中使用该Schema:
@ads_api.route('/test/<parameter>') class test(MethodView): @ads_api.response(200, TestResponseSchema) @ads_api.args(TestQuerySchema, location="query") def get(self, args, parameter): """ testing 额外说明:此接口支持可选查询参数,详情见下方参数列表 """ optional_param = args.get("optional_param") print(parameter, optional_param) if parameter in ['ex1','ex2', 'ex3']: response = {'status':'parameter exists', 'received_optional': optional_param} return response else: abort(404, message='not found')
效果说明
- 方法1的自定义文本会直接显示在Swagger-UI接口的Description区域
- 方法2中Schema定义的参数描述和默认值会自动出现在Swagger的Parameters列表中,同时docstring的内容仍会保留在Description区域
内容的提问来源于stack exchange,提问作者Pawel
相关产品推荐
相关产品推荐

