apidocjs生成api文档实践

coffee

介绍

工作中,见过的api文档有Excel的、有Word的、有pdf的,好的文档会持续维护,但是毕竟是文件,经常传来传去,更新也不及时,还是觉得在线文档更方便。apidoc是一个nodejs库,通过注释生成api文档,文档和代码联系在一起,可以保障文档的及时更新,还支持历史版本追溯,同时因为基于代码注释,多人协作维护起来很方便。

效果

在项目里集成apidoc生成html文档,可以将文档上传到文档服务器后在线查看

api
api

使用

引入

1
npm i apidoc --dev-save

配置

  1. 定义npm脚本build:doc构建api文档
  2. anywhere做静态文件服务器加载文档(为方便,这里没有deploy到文档服务器)
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
{
"name": "wallpaper-node",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build:docs": "npx apidoc -i ./router -o ./docs",
"serve:docs": "npm run build:docs && npx anywhere -p 8080 -s -d ./docs"
},
"dependencies": {
},
"devDependencies": {
"anywhere": "^1.5.0",
"apidoc": "^0.17.7"
},
"apidoc": {
"name": "Wallpaperx API Document",
"title": "Wallpaperx API Document",
"url": "https://api.zequn.tech",
"template": {
"forceLanguage": "en",
"withCompare": false,
"withGenerator": false
}
}
}

定义api

接下来在我们路由定义的方法加入注释,这里是router/album.router.js,加在查询专辑的方法上(示例是nodejs工程,其他语言也可以)

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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
* @api {get} /api/v1/albums Get Albums
* @apiName Get Albums
* @apiGroup Album
*
* @apiParam {String} [channelId] channel id
* @apiParam {String[]} [tags] tag id array
* @apiParam {String} [startAfterId] start after album id, for pagination
* @apiParam {Number} [pageNo] page no, start from 1
* @apiParam {Number} limit page size
* @apiParam {String} [sortBy="-createdAt"] sort by string("+/-" to ASC/DESC, multiple sort is separated with "," )
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* [{
* "id": "5d80a56f5dd15b2e52d02137",
* "channelId": "5d80a56e5dd15b2e52d01ad1",
* "name": "梦幻炫彩简约好看小米手机系统壁纸",
* "description": "梦幻炫彩简约好看小米手机系统壁纸",
* "cover": {
* "url": "http://pic.xiao4j.com/upload/pic/2017_1214/101807732.jpg",
* "width": 1080,
* "height": 1920
* },
* "photos": [
* {
* "url": "http://pic.xiao4j.com/upload/pic/2017_1214/101807732.jpg",
* "width": 1080,
* "height": 1920
* }
* ],
* "count": 20,
* "favoriteCount": 0,
* "tags": [
* {
* "id": "5d80a56f5dd15b2e52d02890",
* "name": "梦幻"
* }
* ],
* "createdAt": 1568712047284,
* "updatedAt": 1568712047284
* }]
*/
albumRouter.get(
'/api/v1/albums',
{
validate: {
query: {
channelId: Joi.string().regex(REGEXS.OBJECT_ID),
tags: Joi.array().items(Joi.string().regex(REGEXS.OBJECT_ID)),
startAfterId: Joi.string().regex(REGEXS.OBJECT_ID),
pageNo: Joi.number().min(1),
limit: Joi.number()
.min(1)
.max(50)
.default(20),
sortBy: Joi.string().default('-createdAt'),
},
},
},
async ctx => {
const { request, response } = ctx
//...
response.ok([])
},
)

最后

最后执行npm run serve:docs,就可以在localhost:8080看到接口文档了。 apidoc是一个很棒的工具,基于apidoc衍生的工具也很多,开发人员多不爱写文档,但是没有文档,一旦代码量上来了,对后续维护的人来说就是一场灾难,将apidoc引入工作流是个不错的选择。