Express集成Swagger自动生成API文档

        上周写接口文档真的是折磨死我了,不是多么困难,是实在麻烦!node实现的http接口,一个对象有好几十个属性,真一言难尽...以前也用过swagger和knife4j,得空就想着能不能在express的接口上面添加swagger,尽量减少接口文档的书写。

        文件夹express_swaggger里面是随手写的测试,懒得新建一个仓库了:

        接口文档效果:个人感觉还行,虽说真的比不上springboot项目便捷。

 

https://github.com/huhengyuan/react_note.git

1. 什么是swagger:

        Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务(<https://swagger.io/>)。 它的主要作用是:

        1. 使得前后端分离开发更加方便,有利于团队协作

        2. 接口的文档在线自动生成,降低后端开发人员编写接口文档的负担

        3. 功能测试 

2. 准备工作:

  • 创建Express项目
npm init -y
npm i express


// 启动文件 -- app.js
// 导入 express 模块
const express = require('express')
// 创建 express 的服务器实例
const app = express()
const os = require('os')
// write your code here...
// const swaggerUi = require('swagger-ui-express');
// const swaggerSpecs = require('./utils/swagger');


const swaggerInstall = require("./utils/swaggers");
swaggerInstall(app);
// 导入 cors 中间件
const cors = require('cors')
// 将 cors 注册为全局中间件
app.use(cors())
// 通过 express.json() 这个中间件,解析表单中的 JSON 格式的数据
app.use(express.json())
app.use(express.urlencoded({ extended: false }))




// 导入并注册用户路由模块
const userRouter = require('./routes/user')
app.use('/api', userRouter)











// 添加Swagger UI界面和API文档路由
// app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpecs));
// 调用 app.listen 方法,指定端口号并启动web服务器
const port = 9752
// 启动服务器监听指定端口
app.listen(port, () => {
    console.log(`app is listen on ` + getIpAddress() + ':' + port)
});
process.on("uncaughtException", (err) => {
    console.log(err);
});



/**
 * 获取当前机器的ip地址
 */
function getIpAddress() {
    var ifaces = os.networkInterfaces()

    for (var key in ifaces) {
        if (key.indexOf('VMware') < 0) {
            let iface = ifaces[key]
            for (let i = 0; i < iface.length; i++) {
                let { family, address, internal } = iface[i]

                if (family === 'IPv4' && address !== '127.0.0.1' && !internal) {
                    return address
                }
            }
        }
    }
}
  • 安装Swagger相关依赖
    npm i swagger-ui-express
    npm i swagger-jsdoc

3. 配置Swagger

  • 创建Swagger配置文件

  • 定义API的描述、版本号、作者信息等

const path = require("path");
const express = require("express");
const swaggerUI = require("swagger-ui-express");
const swaggerDoc = require("swagger-jsdoc");
//配置swagger-jsdoc
const options = {
  definition: {
    openapi: "3.0.0",
    info: {
      title: "Express_Swagger API",
      version: "1.0.0",
      description: `后台接口测试`,
    },
  },
  // 去哪个路由下收集 swagger 注释
  apis: [path.join(__dirname, "../../routes/*.js")],
};

var swaggerJson = function (req, res) {
  res.setHeader("Content-Type", "application/json");
  res.send(swaggerSpec);
};
const swaggerSpec = swaggerDoc(options);

var swaggerInstall = function (app) {
  if (!app) {
    app = express();
  }
  // 开放相关接口,
  app.get("/swagger.json", swaggerJson);
  // 使用 swaggerSpec 生成 swagger 文档页面,并开放在指定路由
  app.use("/swagger", swaggerUI.serve, swaggerUI.setup(swaggerSpec));
};
module.exports = swaggerInstall;

4. 添加Swagger注解

const express = require('express');
const router = express.Router();

/**
 * @swagger
 * tags:
 *   - name: Users
 *     description: API endpoints for managing users
 * /users:
 *   get:
 *     summary: Get all users
 *     tags: [Users]
 *     responses:
 *       '200':
 *         description: Successful response
 */
router.get('/users', (req, res) => {
    // 实现获取用户的逻辑
    res.send('Get all users');
});

/**
 * @swagger
 * /users/{id}:
 *   get:
 *     summary: Get a user by ID
 *     tags: [Users]
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         description: ID of the user
 *         schema:
 *           type: integer
 *     responses:
 *       '200':
 *         description: Successful response
 */
router.get('/users/:id', (req, res) => {
    // 实现获取单个用户的逻辑
    const userId = req.params.id;
    res.send(`Get user with ID ${userId}`);
});


// 登录
/**
 * @swagger
 * /login:
 *   post:
 *     tags: [Users]
 *     summary: "用户登录接口"
 *     consumes:
 *       - application/json
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               userId:
 *                 type: string
 *               password:
 *                 type: string
 *             required:
 *               - userId
 *               - password
 *     responses:
 *       '200':
 *         description: Successful response
 */
router.post('/login', (req, res) => {
    res.send('login OK')
})

module.exports = router;



// const express = require('express')
// // 创建路由对象
// const router = express.Router()

// // 注册新用户
// router.post('/reguser', (req, res) => {
//     res.send('reguser OK')
// })




// /**
//  * @swagger
//  * /users:
//  *   get:
//  *     summary: Get all users
//  *     responses:
//  *       '200':
//  *         description: Successful response
//  */
// router.get('/users', (req, res) => {
//     // 实现获取用户的逻辑
//     res.send('Get all users');
// });


// /**,
//  * @swagger
//  * /test:
//  *    get:
//  *      tags:
//  *      - 小程序端
//  *      summary: 提交考试答案
//  *      produces:
//  *      - application/json
//  *      responses:
//  *        200:
//  *          description: successful operation
//  *          schema:
//  *            ref: #/definitions/Order
//  *        400:
//  *          description: Invalid ID supplied
//  *        404:
//  *          description: Order not found
//  * */
// router.get("/test", function (req, res, next) {
//     res.send("get 提交");
// });

// // 将路由对象共享出去
// module.exports = router

5. 简要步骤:

### express集成swagger步骤

#### 1. 安装swagger需要的相关依赖包swagger-ui-express 和 swagger-jsdoc :

```

    npm i swagger-ui-express

    npm i swagger-jsdoc

```

#### 2. 配置swagger文件:./utils/swaggers/index.js

#### 3. 在启动文件app.js中注册swagger

```

    const swaggerInstall = require("./utils/swaggers");

    swaggerInstall(app);

```

#### 4. 接口上使用注解配置信息 --<>-- express_swagger\routes\user.js

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Swagger 是一个用于构建、文档化和使用 RESTful Web 服务的开源工具。Swagger 有很多版本,其中 Swagger2 是其中最常用的一个版本。Swagger2 可以通过注解的方式生成 API 接口文档,这些注解包括 @Api、@ApiOperation、@ApiParam 等。 下面是使用 Swagger2 生成 API 接口文档的步骤: 1. 添加 Swagger2 依赖 在项目的 pom.xml 文件中添加 Swagger2 的依赖: ``` <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> ``` 2. 配置 Swagger2 在 Spring Boot 应用的启动类上添加 @EnableSwagger2 注解开启 Swagger2 支持,并配置 Docket 对象: ``` @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } } ``` 这个配置会扫描所有的 Controller 类,并生成 API 接口文档。 3. 添加 Swagger2 注解 在 Controller 类的方法上添加 Swagger2 注解,包括: - @Api:用于标识这个 Controller 类的作用和说明。 - @ApiOperation:用于标识这个方法的作用和说明。 - @ApiParam:用于标识方法参数的作用和说明。 示例代码: ``` @RestController @RequestMapping("/api") @Api(value = "HelloWorldController", description = "示例控制器") public class HelloWorldController { @GetMapping("/hello") @ApiOperation(value = "打招呼", notes = "向用户打招呼") public String hello(@ApiParam(name = "name", value = "用户名", required = true) @RequestParam String name) { return "Hello, " + name + "!"; } } ``` 4. 访问 Swagger UI 启动应用后,访问 http://localhost:8080/swagger-ui.html 可以看到 Swagger UI 界面,其中包含了生成的 API 接口文档。在这个界面中,可以查看 API 接口的详细信息、测试 API 接口等。 以上就是使用 Swagger2 生成 API 接口文档的步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值