Rails如何优雅和快速生成API文档

用Rails来写后端API,其实挺方便快捷,并且其自身完备的自动化测试,在不需要打开server的情况下,就能开发出可靠的接口。开发完接口,如果是涉及到多人协作,那这时就需要写API文档了。作为懒是第一生产力的程序员,有没有一种方法让API文档也自动生成呢?

答案是有的!

并且还不少,其中比较出名的是swagger,但测试下来发现,它需要你单独跑一个server并且页面还不是很好看,所以在继续寻找后,发现了一个漂亮好用轻量的方法:

gem dox

优点:

  • 可以与rspec结合,跑一遍测试的同时,把文档也顺带生成了

  • 可以只生成一种API Blueprint language的标记性文档

  • 把文档上传到apipry.io这样的开源工具后,就能生成一份漂亮的在线文档

  • 自动添加各种语言的调用示例代码,返回响应结果:

具体使用方法见gem的方法介绍:https://github.com/infinum/dox

这里要说一说结合https://apipry.io的使用思路:

  • 先在apipry注册账号,新建项目,获取自己的api key/secrets
  • 在自己的项目中添加task代码,用上把生成的api文档,利用apipry提供的api上传到apipry,这里贴一下我的task部分代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
namespace :api do
namespace :doc do
desc 'Generate API documentation markdown'
task :md do
require 'rspec/core/rake_task'
RSpec::Core::RakeTask.new(:api_spec) do |t|
t.pattern = 'spec/controllers/api/v1/'
t.rspec_opts = "-f Dox::Formatter --order defined --tag dox --out public/api/docs/v1/apispec.md --require rails_helper"
end
Rake::Task['api_spec'].invoke
end
task html: :md do
`aglio -i public/api/docs/v1/apispec.md -o public/api/docs/v1/index.html`
end
task open: :html do
`open public/api/docs/v1/index.html`
end
task open: :html do
`open public/api/docs/v1/index.html`
end
task publish: :md do
api_sub_do = 'qingbao'
values = {
code: File.read("public/api/docs/v1/apispec.md")
}
headers = {
'Content-Type': 'application/json; charset=utf-8',
'Authentication': 'Token a28946ac46b80866fxxxxxxxxxxxxx'
}
begin
response = RestClient.post "https://api.apiary.io/blueprint/publish/#{api_sub_do}", values.to_json, headers
puts response
rescue RestClient::ExceptionWithResponse => err
puts err.response
end
end
end
end