温馨提示×

linux swagger怎么测试接口

小樊
38
2026-10-24 04:45:41
栏目: 智能运维

在 Linux 环境下测试 Swagger(OpenAPI)接口,通常有三种常见方式:


一、通过 Swagger UI 在浏览器中测试(最简单)

如果你的服务已经集成了 Swagger UI(如 Spring Boot、FastAPI、Node.js 等):

  1. 启动服务
  2. 浏览器访问:
    http://ip:端口/swagger-ui.html
    
    或
    http://ip:端口/swagger-ui/index.html
    
  3. 找到对应接口 → 点击 Try it out → 填写参数 → Execute

如果是远程 Linux 服务器,可用:

ssh -L 8080:localhost:8080 user@server

然后本地浏览器访问 http://localhost:8080/swagger-ui.html


二、使用 curl 直接测试接口(Linux 最常用)

Swagger 本质就是 HTTP 接口。

1️⃣ 查看 Swagger 文档(JSON)

curl http://localhost:8080/v3/api-docs

2️⃣ 测试一个 GET 接口

curl http://localhost:8080/api/user/1

3️⃣ 测试 POST 接口(JSON)

curl -X POST http://localhost:8080/api/login \
  -H "Content-Type: application/json" \
  -d '{"username":"admin","password":"123456"}'

4️⃣ 带 Token 测试

curl http://localhost:8080/api/user \
  -H "Authorization: Bearer eyJhbGciOi..."

三、使用 swagger-codegen / openapi-generator(自动化测试)

适合接口很多或写脚本测试。

安装

pip install openapi-generator-cli

生成客户端

openapi-generator-cli generate \
  -i http://localhost:8080/v3/api-docs \
  -g python \
  -o ./client

然后直接用生成的 SDK 写测试代码。


四、使用 Postman / Hoppscotch(推荐)

  • Postman(Linux 有桌面版 / CLI)
  • Hoppscotch(浏览器,轻量)

导入 Swagger JSON:

http://ip:port/v3/api-docs

五、常见问题

✅ Linux 无界面
→ 用 curl 或 swagger JSON + Postman CLI

✅ 接口需要登录
→ 先调登录接口拿 token,再带 header

✅ 跨服务器访问不了
→ 检查防火墙 / 端口 / 反向代理


如果你愿意,可以告诉我:

  • 用的什么框架(Spring Boot / FastAPI / Node)
  • Swagger 地址
  • 想测哪个接口

我可以给你精确的测试命令。

0 踩