温馨提示×

ubuntu swagger有没有案例

小樊
51
2025-10-05 16:00:57
栏目: 智能运维

Ubuntu环境下Swagger的常见使用案例

1. 快速搭建Swagger UI服务(Express框架+YAML配置)

适用于需要自定义API文档界面的开发场景,通过Express整合Swagger UI,实现本地API文档的可视化与测试。

  • 前置准备:安装Node.js和npm(sudo apt update && sudo apt install nodejs npm)。
  • 安装依赖:通过npm安装Express、Swagger UI中间件及YAML解析工具(sudo npm install -g swagger-ui-express yamljs)。
  • 创建Express应用:编写app.js文件,加载Swagger文档(如swagger.yaml)并通过/api-docs端点提供访问:
    const express = require('express');
    const swaggerUi = require('swagger-ui-express');
    const YAML = require('yamljs');
    const app = express();
    const swaggerDocument = YAML.load('./swagger.yaml'); // 加载Swagger定义
    app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
    app.listen(3000, () => console.log('Server running on port 3000'));
    
  • 编写Swagger定义:创建swagger.yaml文件,定义API基本信息(标题、版本)、主机地址、路径及响应格式(如/users接口的GET请求返回用户列表)。
  • 启动与访问:运行node app.js启动服务,浏览器访问http://localhost:3000/api-docs即可查看交互式API文档。

2. 使用Docker快速部署Swagger UI

适用于希望避免环境配置复杂度的场景,通过Docker容器快速启动Swagger UI服务。

  • 安装Docker:通过sudo apt update && sudo apt install docker.io安装Docker。
  • 拉取镜像:从Docker Hub获取Swagger UI镜像(docker pull swaggerapi/swagger-ui)。
  • 运行容器:将本地Swagger文档(如/path/to/swagger.json)挂载至容器,并映射端口(docker run -p 80:8080 -v /path/to/swagger.json:/usr/src/app/swagger.json swaggerapi/swagger-ui)。
  • 访问服务:浏览器访问http://localhost即可查看Swagger UI界面,直接加载挂载的Swagger文档。

3. 结合Spring Boot项目的自动化集成

适用于Java Spring Boot开发者,通过注解自动生成Swagger文档,实现代码与文档同步。

  • 添加依赖:在pom.xml中引入Springfox Swagger2和Swagger UI依赖(如springfox-boot-starter)。
  • 配置Swagger:创建配置类(如SwaggerConfig.java),指定API分组、扫描路径及文档信息(标题、描述、版本)。
  • 编写Controller:在Controller类中使用Swagger注解(如@Api@ApiOperation@ApiResponse)标注接口信息。
  • 启动与访问:运行Spring Boot应用(./mvnw spring-boot:run),浏览器访问http://localhost:8080/swagger-ui.html即可查看自动生成的API文档。

4. Swagger Editor文档编辑与测试

适用于API设计阶段,通过Swagger Editor可视化编写Swagger文档并实时测试接口。

  • 安装Swagger Editor:通过npm全局安装(sudo npm install -g swagger-editor)或下载源码解压。
  • 启动Editor:运行swagger-editor命令,浏览器自动打开http://localhost:8080
  • 编辑与测试:在Editor中编写或导入Swagger YAML/JSON文件,实时预览文档效果;点击接口右侧的“Try it out”按钮,输入参数并执行测试,查看响应结果。

0