在 Debian 上使用 Swagger 进行 API 测试的实用流程
一 准备环境
- 更新系统并安装基础工具:sudo apt update && sudo apt install -y curl nodejs npm python3 python3-pip。
- 确认版本:node -v、npm -v、python3 --version。
- 准备 API 规范文件:建议使用 OpenAPI 2.0/3.0 的 swagger.json 或 swagger.yaml,可从后端项目导出或自行编写。
二 方式一 使用 Swagger UI Express 本地托管文档并直接调试
- 安装依赖:npm install express swagger-ui-express yamljs。
- 目录与文件:创建目录(如 swagger-ui),放入 swagger.yaml/swagger.json。
- 启动服务示例(app.js):
const express = require(‘express’);
const swaggerUi = require(‘swagger-ui-express’);
const YAML = require(‘yamljs’);
const swaggerDocument = YAML.load(‘./swagger.yaml’);
const app = express();
app.use(‘/api-docs’, swaggerUi.serve, swaggerUi.setup(swaggerDocument));
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(Swagger UI: http://localhost:${PORT}/api-docs));
- 运行与访问:node app.js,浏览器打开 http://localhost:3000/api-docs,在页面中点击 Try it out 直接发送请求。
三 方式二 使用 Docker 快速运行 Swagger UI
- 安装 Docker:sudo apt install -y docker.io。
- 启动容器(将本地规范挂载到容器):
docker run --name swagger-ui -d -p 8080:8080 \
-e SWAGGER_JSON=/spec/swagger.yaml \
-v $(pwd)/swagger.yaml:/spec/swagger.yaml \
swaggerapi/swagger-ui
- 访问:浏览器打开 http://localhost:8080。
四 方式三 使用 Swagger Codegen 生成客户端并做自动化测试
- 安装代码生成工具:pip3 install swagger-codegen。
- 生成客户端(示例生成 JavaScript 客户端):
swagger-codegen generate -i ./swagger.yaml -l javascript -o ./generated-client。
- 编写测试(示例用 Jest + Supertest):
npm install --save-dev jest supertest
在测试文件中:
const request = require(‘supertest’);
const app = require(‘…/app’); // 你的后端服务
describe(‘GET /api/items’, () => {
it(‘returns 200 and json’, async () => {
const res = await request(app).get(‘/api/items’);
expect(res.statusCode).toBe(200);
expect(res.headers[‘content-type’]).toMatch(/json/);
});
});
- 运行测试:npx jest。
五 命令行与进阶建议
- 快速验证接口(curl):
- GET:curl -X GET http://localhost:3000/api/users
- POST:curl -X POST http://localhost:3000/api/users \
-H “Content-Type: application/json” \
-d ‘{“name”:“Alice”,“email”:“alice@example.com”}’
- 安全与规范:
- 生产环境应限制对 /api-docs 的访问(如反向代理鉴权、IP 白名单)。
- 规范 host/basePath/schemes,避免跨域与请求失败。
- 可使用 APIDetector 等工具识别公开暴露的 Swagger 端点,及时收敛风险。