如何让Rswag在生成的Swagger文档中显示响应Schema?
问题
使用Rswag gem创建Swagger OpenAPI规范时,编写了/api/v2/ping接口的GET请求响应定义,包含响应头、Schema及示例,但生成的文档中响应示例旁未显示对应的模型,请问如何让响应Schema正常显示?
相关代码示例:
path '/api/v2/ping' do get('returns a response when pinged') do tags 'Ping' consumes 'application/json' security [bearerAuth: []] parameter name: :Authorization, in: :header, type: :string description 'Ping the API' response(200, 'successful') do header 'X-Rate-Limit-Limit', schema: { type: :integer }, description: 'The number of allowed requests in the current period' header 'X-Rate-Limit-Remaining', schema: { type: :integer }, description: 'The number of remaining requests in the current period' schema type: :object, properties: { ok: { type: :boolean } } example 'application/json', :example, { ok: true }, 'Ping', 'A successful ping!' run_test! end ...
解决方法
方法1:将Schema定义为可复用组件并引用
Swagger UI会自动识别components中定义的Schema为可展示模型,具体修改步骤如下:
- 在swagger根定义中添加
components块,预定义响应模型:
components do schema 'PingResponse' do type :object properties do ok :boolean, description: '请求是否成功的标识' end end end
- 在响应的schema中通过
$ref引用这个预定义模型:
response(200, 'successful') do header 'X-Rate-Limit-Limit', schema: { type: :integer }, description: '当前周期内允许的请求总数' header 'X-Rate-Limit-Remaining', schema: { type: :integer }, description: '当前周期内剩余的请求数' # 引用预定义的Schema组件 schema '$ref' => '#/components/schemas/PingResponse' example 'application/json', :example, { ok: true }, 'Ping', '请求成功的响应示例' run_test! end
方法2:修正内联Schema的示例关联(适用于无需复用Schema的场景)
如果坚持使用内联Schema,需确保示例与Schema结构完全匹配,同时可改用examples块明确关联:
response(200, 'successful') do header 'X-Rate-Limit-Limit', schema: { type: :integer }, description: '当前周期内允许的请求总数' header 'X-Rate-Limit-Remaining', schema: { type: :integer }, description: '当前周期内剩余的请求数' schema type: :object, properties: { ok: { type: :boolean } } # 改用examples块定义,明确关联当前Schema examples 'application/json' => { :example => { summary: 'Ping', description: 'A successful ping!', value: { ok: true } } } run_test! end
额外注意事项
- 确保Rswag gem为最新版本,旧版本可能存在Schema与示例关联的兼容性问题
- 重新生成文档前可清理缓存,避免Swagger UI渲染旧内容
内容的提问来源于stack exchange,提问作者Cameron
相关产品推荐
相关产品推荐

