Swagger UI是测试Swagger API最直观的工具,支持可视化操作和实时响应验证。
sudo apt update && sudo apt install -y nodejs npm
swagger-ui-express(用于集成Swagger UI到Node.js应用)。sudo npm install -g swagger-ui-express
swagger.json(或swagger.yaml)文件,定义API接口规范(如端点、参数、响应格式)。示例如下:{
"swagger": "2.0",
"info": {"title": "Sample API", "version": "1.0.0"},
"basePath": "/api",
"paths": {
"/users": {
"get": {
"summary": "获取所有用户",
"responses": {"200": {"description": "用户列表"}}
}
}
}
}
// app.js
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)); // 映射Swagger UI路径
app.listen(3000, () => console.log('Swagger UI运行在 http://localhost:3000/api-docs'));
node app.js
http://localhost:3000/api-docs,在Swagger UI界面中找到目标接口,点击Try it out按钮,输入参数(如路径变量、请求体),即可查看实时响应结果。对于简单接口或自动化场景,可使用curl命令直接发送HTTP请求,验证API功能。
curl -X GET http://localhost:3000/api/users
curl -X POST http://localhost:3000/api/users \
-H "Content-Type: application/json" \
-d '{"name": "Alice", "email": "alice@example.com"}'
curl -X GET http://localhost:3000/api/users/1
注意:若接口需要认证,需在curl命令中添加认证信息(如-H "Authorization: Bearer <token>")。对于复杂场景(如回归测试、性能测试),可使用HttpRunner等自动化框架,基于Swagger文档生成测试用例并批量执行。
pip install httprunner
hrp命令,根据Swagger文档生成YAML/JSON格式的测试用例。hrp init tests/test_example.yml
hrp gen-swagger -s http://localhost:3000/api-docs -o tests/test_example.yml
hrp run tests/test_example.yml --report html
HttpRunner会自动解析Swagger文档中的接口信息,生成包含请求参数、预期结果的测试用例,提升测试效率。若需测试Swagger API的安全性,可使用以下工具:
git clone https://github.com/brinhosa/apidetector.git
cd apidetector
pip install -r requirements.txt
python apidetector.py -d example.com # 替换为目标域名
swagger.json/swagger.yaml),确保测试用例与实际接口一致。