Skip to content

接口文档

  • 什么是接口文档?

“接口文档”又称为“API文档”,是用来描述服务端所提供接口信息的文档 通过接口文档我们可以告诉其他开发人员发送什么类型的请求,传递射门类型的参数,到什么地址能够得到什么样的数据

  • 为什么要编写接口文档?

    • 企业开发中不是单打独斗,而是团队协作,在企业开发中,接口文档就是前端开发人员与后端开发人员沟通的桥梁 通过这个桥梁可以让前后端开发人员更改的配合,提高工作效率
    • 企业开发不可避免的需要对项目进行迭代更新,不可避免的会有人员流动, 通过接口文档可以在项目迭代更新或者项目人员流动时,提升代码可维护性
  • 如何编写接口文档?

    • 过去:记事本/word文本工具编写
    • 现在:借助三方工具/框架编写

第三方工具

  • apidoc
    • apidoc是一个根据注释自动生成Restful web Api文档工具
    • 特点:
      1. 跨语言,JS、GO、Java、C++、rust等大部分开发语言
      2. 跨平台,linux、windows、macOs等都支持
      3. 支持语言广泛,即使是不支持,也很方便扩展
      4. 支持多个不同语言的多个项目生成一份文档

apidoc

安装

shell

npm install grunt-apidoc --save-dev

package.json中进行如下配置,或者单独创建一个apidoc.json

apidoc.json

json
{
  "name": "example",
  "version": "0.1.0",
  "description": "apiDoc basic example",
  "title": "Custom apiDoc browser title",
  "url" : "https://api.github.com/v1"
}

package.json

json
{
  "apidoc": {
    "name": "example",
    "version": "0.1.0",
    "description": "apiDoc basic example",
    "apidoc": {
      "title": "Custom apiDoc browser title",
      "url" : "https://api.github.com/v1"
    }
  }
}

需要在package.json中添加如下的一条命令

json
{
  "scripts": {
    "doc": "apidoc -i app/controller -o app/public/apidoc"
  }
}

使用

  • @api {method} path [title]

    1. @api:这是一个api
    2. {method} 请求方式 {get} {post} ... 必须带着{}
    3. path 请求地址
    4. 请求描述
  • @apiName name

    1. @apiName: 定义当前方法的名称api
    2. name : 这里填写对应的名称
  • @apiGroup name:对当前的路由进行分组

  • @apiSampleRequest url:接口请求示例,参数为完整的请求地址

  • @apiParam {类型} 参数名称 参数描述:可以写多个

    1. 如果需要参数可选,需要将参数名称用[参数名称]括起来
    2. 默认参数 参数名称=默认值
  • @apiSuccess {成功类型} 成功参数名称 成功的描述 : 可以写多个

  • @apiSuccessExample Success-Response: 成功的响应

@apiSuccessExample Success-Response:
     HTTP/1.1 200 OK
     {
       "firstname": "John",
       "lastname": "Doe"
     }
  • @apiError SenMsgError 发送短信失败

  • @apiErrorExample Error-Response:

 @apiErrorExample Error-Response:
     HTTP/1.1 404 Not Found
     {
       "error": "UserNotFound"
     }
  • 解决冗余的代码@apiDefine
js
/**
 * @apiDefine 定义的公用的名称
 * @apiSuccess {String} status 请求状态描述 
 * @apiSuccess {Integer} code 请求状态码
 * ...
 */
// 在文件中使用

/**
 * @apiUse 定义的公用的模块
*/

在配置中排序:需要在package.json中添加一个order

json

{
  "apidoc": {
    "order": [
      "User",
      "Util"
    ]
  }
}

第三方框架(swagger)

官网地址

swagger是一款基于yaml和json自动生成Restful web Api的框架

安装

shell
npm install swagger-jsdoc # 将注释转换成swagger需要的json、

npm install koa2-swagger-ui --save # 用于生成swagger-ui

需要新建一个app.ts

ts
const swaggerJsDoc = require('swagger-jsdoc')

import  {koaSwagger} from 'koa2-swagger-ui'
module.exports = (app)=>{
    const swaggerDefinition = {
        info:{
            title:'测试',
            version:'1.1.1',
            description:'描述'
        },
        host:'127.0.0.1:7002',
        basePath:'/api/v1', //冗余的接口地址前缀
        schemes:['http','https']
    }
    const options = {
        swaggerDefinition,
        // 告诉swagger哪些文件的注释,需要转成swagger需要的json
        apis:['./app/swagger/*.ts','./app/controller/*.ts'],//写有注释文件存放地址
    }
    const swaggerSpec = swaggerJsDoc(options);
    // 指定从什么地方可以获取到生成的json文件
    app.router.get('/swagger.json',async function (ctx) {
        ctx.set('Content-type','application/json');
        ctx.body = swaggerSpec;
    })
    // 注册koa2-swagger-ui,方便我们访问文档
    app.use(
        koaSwagger({
            // 访问什么地址展示生成的文档
            // http://127.0.0.1/swagger
            routePrefix:'/swagger',
            // 告诉去哪获取swagger.json
            swaggerOptions:{
                url:'/swagger.json'
            }
        })
    )
}

使用

OpenApi规范

ts

// 遵守OpenApi


/**
 * @swagger
 * definition:
 *   SmsData:
 *     type:"object"
 *     properties:
 *       ...
 */

/**
 * @swagger
 * definition:
 *   SmsResult:
 *     type: "object"
 *     properties:
 *       status:
 *         type: "string"
 *         description: "英文状态描述"
 *         msg:
 *           type: "string"
 *           description: "中文状态描述"
 *         code:
 *           type: "number"
 *           description: "返回状态码"
 *         data:
 *           $ref: "#/definitions/SmsData"
 */

/**
 * @swagger
 * /smscode:
 *   get:
 *     tags:
 *     - '工具类'
 *     summary:'发送短信验证码'
 *     description:'发送4为短信验证码'
 *     parameters:
 *     - in: "query" 
 *       name: "string"
 *       type: "string"
 *       required: true
 *       description: "接收短信的手机号"
 *     produces:
 *       - "application/json"
 *       response:
 *         "200":
 *           description: "发送短信成功"
 *           schema:
 *           $ref: "@/definitions/SmsResult"
 */

  • in中代码的含义
    1. query 代表参数在连接上例如:/smscode?mobile=xxx或者/smscode/:mobile相当于/smscode/xxxx
    2. path
    3. body 通过请求体

Released under the MIT License.