在Ubuntu系统上,Postman提供了**图形界面(GUI)和命令行(Newman)**两种方式实现API监控,覆盖手动触发、定期自动运行及结果分析等场景。以下是具体操作步骤:
.tar.gz格式安装包(如Postman-linux-x64-*.tar.gz)。/opt/目录:sudo tar -xzf Postman-linux-x64-*.tar.gz -C /opt/
sudo ln -s /opt/Postman/Postman /usr/bin/postman # 全局命令
sudo nano /usr/share/applications/postman.desktop # 创建桌面图标
在编辑器中粘贴以下内容(替换图标路径),保存后即可从应用菜单打开Postman:[Desktop Entry]
Encoding=UTF-8
Name=Postman
Exec=/usr/bin/postman
Icon=/opt/Postman/app/resources/app/assets/icon.png
Terminal=false
Type=Application
Categories=Development;
Postman的**Monitor(监视器)**功能可定期运行API集合,监控其健康状况(状态码、响应时间、返回数据等)。
https://api.example.com/users),设置请求头(如Content-Type: application/json)、请求体(如JSON参数),点击“Send”验证接口连通性。MyAPIs),将请求添加至集合中(便于批量管理)。User API Monitoring);MyAPIs);base_url),可选择对应的.env文件;UTC+8)。若需将API监控集成至CI/CD流程(如Jenkins、GitLab CI),可使用Postman的命令行工具Newman。
npm install -g newman
Collection v2.1,保存为my_collection.json;base_url),同样导出环境文件(my_environment.json)。./reports目录):newman run my_collection.json -e my_environment.json -r html --reporter-html-export ./reports/report.html
crontab -e),添加以下内容(每5分钟运行一次):*/5 * * * * /usr/local/bin/newman run /path/to/my_collection.json -e /path/to/my_environment.json -r html --reporter-html-export /path/to/reports/report_$(date +\%F_\%H\%M).html
// 检查状态码是否为200
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
// 检查响应时间是否小于200ms
pm.test("Response time is less than 200ms", function () {
pm.expect(pm.response.responseTime).to.be.below(200);
});
// 检查响应体是否包含特定字段
pm.test("Response contains user data", function () {
const jsonData = pm.response.json();
pm.expect(jsonData).to.have.property("id");
pm.expect(jsonData).to.have.property("name");
});
通过以上步骤,即可在Ubuntu系统上使用Postman实现API监控,无论是手动触发还是自动化运行,都能有效保障API的稳定性与性能。