众所周知,rails 可以使用 rails routs生成下面这样的接口文档,可以在启动的服务页面打开(/rails/info/routes),但是文档中只有api的路径,不能直接导入api fox进行测试,非常麻烦,所以找了下.发现可以使用swagger-blocks来实现导入功能
1.项目中引入
#gem文件中添加这行
gem "swagger-blocks"
# 安装依赖
bundle
2.在routes中引入api路径
在config/routes.rb中生成叫/apidocs路径的方法,使用控制器中的index方法
这样,我们可以在baseUrl/apidocs中拿到渲染成swager格式的文档
Rails.application.routes.draw do
resources :apidocs, only: [:index]
end
end
3.创建 ApidocsController
根据rails规范,在/controllers目录中创建apidocs_controller.rb文件
- 并写下以下代码,作用是当请求地址为
/apidocs,渲染Swagger::Blocks.build_root_json(SWAGGERED_CLASSES)方法返回的json - swagger_root 为swagger规范的描述
注意 : SWAGGERED_CLASSES为控制器的集合,必须写上self,否则拿不到自己定义的swagger_root方法
require "swagger/blocks"
class ApidocsController < ActionController::Base
include Swagger::Blocks
swagger_root do
key :swagger, "2.0"
end
# A list of all classes that have swagger_* declarations.
SWAGGERED_CLASSES = [
# Api::V1::ValidationCodesController,
Api::V1::ItemsController,
self,
].freeze
def index
# render json: Swagger::Blocks.build_root_json(SWAGGERED_CLASSES)
render json: Swagger::Blocks.build_root_json(SWAGGERED_CLASSES)
end
end
4.在Api::V1::ItemsController中描述接口详情
以分页器功能举例,注意不要忘了添加 include Swagger::Blocks
class Api::V1::ItemsController < ApplicationController
include Swagger::Blocks
swagger_path "/api/v1/items" do
operation :post do
end
end
swagger_path "/api/v1/items" do
operation :get do
key :description, "查询"
end
end
def index
items = Item.page(params[:page] || 1 ).per(params[:page_size] || 10)
render json: { resource: items ,pager:{
page:params[:page],
page_no:params[:page_size],
count:Item.count,
}}
end
def create
item = Item.new amount: 1
if item.save
render json: { resource: item }
else
render json: { errors: item.errors }
end
end
end
5.Api Fox中导入JSON
点击确定
直接生成Ruby On Rails 将生成的接口自动导入API FOX