在Debian上利用Swagger进行API测试可参考以下步骤:
安装工具
sudo apt update
sudo apt install nodejs npm
npm install -g swagger-jsdoc swagger-ui-express
pip3 install swagger-ui-express swagger-codegen
创建Swagger配置文件
编写swagger.json
或swagger.yaml
,定义API路径、参数、响应等,例如:
{
"swagger": "2.0",
"info": {"title": "Sample API", "version": "1.0.0"},
"paths": {
"/users": {
"get": {
"summary": "获取用户列表",
"responses": {
"200": {"description": "用户列表", "schema": {"type": "array"}}
}
}
}
}
}
集成Swagger到应用
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerDoc = require('./swagger.json');
const app = express();
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDoc));
app.listen(3000, () => console.log('服务已启动,访问 http://localhost:3000/api-docs'))
启动服务并测试
http://localhost:3000/api-docs
),可查看接口文档并直接测试接口。curl
或Postman等工具调用接口,例如:curl -X GET http://localhost:3000/users
自动化测试(可选)
通过Swagger Codegen生成客户端代码,或使用脚本解析swagger.json
批量生成测试用例。
注意:确保API服务与Swagger UI的端口配置正确,生产环境需限制Swagger UI的访问权限。