apidoc 是一款根據代碼上的注釋自動生成接口文檔的工具,它支持多種語言,以下JavaScript示例;
注釋需要按照 apidoc 官網注釋規則;
1. 全局安裝 apidoc
npm install apidoc -g
2.寫注釋 官網字段說明
以下是我寫得比較完整的一個注釋
/**
* @apiDefine apiSuccess 成功統一返回參數
* @apiSuccess {String} code code
* @apiSuccess {String} msg msg
* @apiSuccess {Object} data config data
* */
/** * @api {get} /config config(接口名稱) * @apiGroup api * @apiName getConfig(該字段不影響文檔顯示) * @apiDescription (接口描述)2.9.3起新config接口 * @apiVersion 2.2.2(接口版本) * * @apiHeader {String} system 系統 * @apiHeader {String} version 版本號 * * @apiHeaderExample {json} Header-Example: * { * "system": "ios", * "version": "2.2.2" * } * * @apiUse apiSuccess * * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * { * "code": 0, * "msg": "", * "data": { * "id": 111, * "system": "ios", * "version": "2.2.2", * "status": "0" * } * } * * */
3. 添加配置文件 apidoc.json 文件 官網字段說明
{ "name": "接口名稱",
"title":"文檔標題"
"version": "2.2.2", "description": "文檔描述", "url" : "http://qa.api.test.com/", // api路徑的前綴 "sampleUrl": "http://qa.api.test.com/", // 如果設置了此選項,則將顯示用於測試api方法(發送請求)的表單。 "template": { "withCompare": true, "withGenerator": true } }
4. 輸入命令,生成文檔 官網字段說明
// apidoc -i 指定讀取源文件的目錄 -o 指定輸出文檔的目錄 apidoc -i src/ -o apidoc/
根據我命令,在項目里會生成 apidoc 文件夾,該文件夾下 index.html 就是接口文檔;
5. (本步驟可自選) 在 package.json 文件設置 scripts,這樣就不用再記命令了,運行 npm run apidoc 文檔生成;
apidoc 的 html 文件轉 markdown 文件 -- apidoc-markdown
apidoc-markdown 是一個根據apidoc輸出文件直接生成markdown文件的工具。
1. 全局安裝
npm install apidoc-markdown -g
2.運行命令 更全字段官網
// apidoc-markdown -p apidoc 文件夾路徑 -o md文件生成路徑 -t 使用模板路徑 apidoc-markdown -p public/apidoc -o public/doc_markdown.md -t public/templates/default_cn.md
以上沒有指定md的模板,默認使用其自帶的md模板文件,對於 apidoc 中 api_data.json 文件的有些字段無法識別,最終生成的md文件不完整;
需要自行使用 EJS模板文件,然鵝我沒找到現成的支持 apidoc 轉 md 的模板文件,所以就把默認的模板文件稍微修改了一下;
我在用默認的模板文件轉 md 時遇到了 可選 參數轉換問題,具體體現如下:
轉后的 md 文件顯示:
apidoc api_data.json 文件 :
apidoc-markdown 默認模板文件 修改前:
### Headers | Name | Type | Description | |---------|-----------|--------------------------------------| <% sub.header.fields.Header.forEach(header => { -%> | <%- header.field %> | <%- header.type ? `\`${header.type}\`` : '' %> | <%- header.optional ? '**optional**' : '' %><%- header.description %> | <% }) // foreach parameter -%> <% } // if parameters -%> <% if (sub.header && sub.header.examples && sub.header.examples.length) { -%>
apidoc-markdown 默認模板文件 修改后:
### Headers | Name | Type | Optional | Description | |---------|-----------|-----------|--------------------------------------| <% sub.header.fields.Header.forEach(header => { -%> | <%- header.field %> | <%- header.type ? `\`${header.type}\`` : '' %> | <%- header.optional ? '可選' : '' %> | <%- header.description %> | <% }) // foreach parameter -%> <% } // if parameters -%> <% if (sub.header && sub.header.examples && sub.header.examples.length) { -%>
修改后 md文件: