写文档是开发者经常要做的事情,今天介绍一个自动生成文档的工具apidoc。使用起来非常简单,一键快速生成文档,操作非常方便。
安装:npm install apidoc -g
在需要写文档的目录编写配置文件apidoc.json:{
"name": "接口文档名称",
"version": "1.0.0",
"description": "接口文档描述",
"title": "接口文档浏览器标题",
"url" : "http://api.abc.com/",
"header": {
"title": "接口通用规则",
"filename": "../header.md"
},
"footer": {
"title": "API 错误返回值说明",
"filename": "../footer.md"
}
}
上面的例子引入了公共的头部和底部,支持md模式:
footer.md:# API 错误返回值说明
## 错误返回示例
{
"code" : -1,
"msg" : "params missing",
}
## HTTP 状态码
code | 描述 | 说明
--- | --- | ---
-1 | 错误提交 | 具体看返回的错误信息
401 | 鉴权失败 | access_token过期或者不正确,重新登录
404 | 路由不存在或者资源不存在 | 访问的url不存在或者对应资源不存在
500 | 服务器内部错误 | 内部服务器出错
header.md:## API 调用规则
本文档中所有请求服务端 API 接口的请求均使用此规则校验,以下不再重复说明。
API 接口统一请求URL ```http://api.abc.com/```
每次请求 API 接口时,均需要提供 HTTP Request Header,具体如下:
名称 | 类型 | 说明
--- | --- | ---
```nonce``` | String | 随机生成的```32```位数字
```timestamp``` | String | 客户端时间,时间戳
```auth``` | String | ```(选填)```不需用户登录的 API 不传该项,如需用户登录的 API ,需要传该项
```sign``` | String | 数据签名。
header和footer是选填的,可以没有!
使用(将api目录下面的接口在html目录生成文档):apicod -i api/ -o html/
如果api目录下面没有接口文件则会返回错误信息
{"Path":"D:\\xds\\xxxxx\\test","level":"error","message":"No files found."}
写入一个测试接口goods.php:/**
* @apiVersion 1.0.0
* @api {post} goods.php 获取商品
* @apiName goods_list
* @apiGroup Goods
* @apiParam {String} r goods.goods_list
* @apiParam {Number} [page] 页码 默认为1
* @apiParam {String} [keywords] 搜索关键词 默认为空
* @apiParam {String} [order] 按什么排序 sales 按销量 minprice 按价格 createtime 按时间 空为默认按时间倒序排序
* @apiParam {String} [by] 搜索排序 desc 倒序 asc为顺序 默认desc
*
* @apiSuccess {Number} code 返回信息码 200 表示请求成功
* @apiSuccess {String} msg 返回说明信息
* @apiSuccess {String} data 返回的数据
*
* @apiSuccessExample Success-Response:
* {"code":0,"msg":"ok","data":{"goods_list":[{"gid":"123","title":"测试商品","thumb":"http://abc/test.jpg","fake_price":"650.00","price":"205.00","min_price":"45.00","max_price":"75.00","is_discount":"0","sales":"10","total":"99","desc":"商品描述"}],"total":"30","page_size":10}}
*
*/
/**
* @apiVersion 1.0.0
* @api {post} goods.php 收藏商品
* @apiName collect_goods
* @apiGroup Goods
* @apiParam {String} r goods.collect_goods
* @apiParam {Number} gid 商品编号
*
* @apiSuccess {Number} code 返回信息码 200 表示请求成功
* @apiSuccess {String} msg 返回说明信息
*
* @apiSuccessExample Success-Response:
* {"code":0,"msg":"ok"}
*
*/
目录结构:
(demo在附件)
重新运行生成命令:apidoc -i api/ -o html/
然后在html里面可以直接访问index.html查看文档了
注意:每次更新了接口文件都需要重新执行生成apidoc命令生成。