温馨提示×

Linux Swagger怎么测试

小樊
35
2026-08-05 21:33:02
栏目: 智能运维

在 Linux 下测试 Swagger(OpenAPI)接口,常见做法有几种,取决于你是查看 Swagger 文档调用接口,还是自动化测试。下面按常用场景给你一个完整说明。


一、最常见方式:浏览器访问 Swagger UI(推荐)

1️⃣ 启动服务后访问 Swagger UI

如果你的后端已经集成 Swagger(如 Spring Boot / FastAPI / Gin + Swagger),通常可以直接访问:

http://服务器IP:端口/swagger-ui.html
# 或
http://服务器IP:端口/swagger-ui/
# 或
http://服务器IP:端口/docs

举例:

http://localhost:8080/swagger-ui.html

✅ 优点:

  • 可视化
  • 可直接填参数、点 Try it out
  • 不需要额外工具

二、Linux 命令行测试 Swagger 接口(无浏览器)

方式 1:用 curl 测试接口(最常用)

1️⃣ 先查看 Swagger JSON

curl http://localhost:8080/v2/api-docs
# 或
curl http://localhost:8080/v3/api-docs

你会得到一个 OpenAPI JSON 文件。

2️⃣ 根据 JSON 里的接口直接测试

例如接口是:

POST /api/user

测试:

curl -X POST http://localhost:8080/api/user \
  -H "Content-Type: application/json" \
  -d '{"name":"test","age":18}'

✅ 适合:

  • 服务器环境
  • CI/CD
  • 快速验证

方式 2:用 httpie(比 curl 更友好)

安装:

sudo apt install httpie
# 或
sudo yum install httpie

测试:

http POST http://localhost:8080/api/user name=test age=18

三、用 Swagger Codegen / OpenAPI Generator 测试

1️⃣ 下载 OpenAPI 描述文件

curl http://localhost:8080/v3/api-docs > openapi.json

2️⃣ 生成客户端(可选)

openapi-generator generate \
  -i openapi.json \
  -g python \
  -o ./client

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

✅ 适合:

  • 自动化测试
  • 多语言调用

四、用 Swagger Editor(Linux 本地)

1️⃣ Docker 方式运行

docker run -d -p 8081:8080 swaggerapi/swagger-editor

访问:

http://localhost:8081

✅ 可:

  • 编辑 OpenAPI
  • 直接测试接口

五、用 Postman / Insomnia(Linux 也有)

Postman

wget https://dl.pstmn.io/download/latest/linux64 -O postman.tar.gz
tar -xzf postman.tar.gz
./Postman/Postman

导入:

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

六、Spring Boot 项目常见 Swagger 测试示例

Springfox / springdoc-openapi

类型 地址
Swagger UI /swagger-ui.html
API JSON /v2/api-docs/v3/api-docs

测试:

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

七、常见问题排查

❌ 访问不了 Swagger

  • 是否被 Spring Security 拦截?
  • 是否加了:
@EnableOpenApi
  • 是否生产环境关闭了 Swagger?

❌ 403 / 401

curl -H "Authorization: Bearer xxx" http://localhost:8080/api/test

八、总结(快速选择)

场景 推荐方式
本机 / 有桌面 浏览器 Swagger UI
Linux 服务器 curl / httpie
自动化测试 OpenAPI Generator
API 设计 Swagger Editor
复杂接口 Postman

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

  • ✅ 你用的是 Spring Boot / FastAPI / Gin / Node
  • ✅ Swagger 版本(2.x 还是 3.x)?
  • ✅ 是本机还是远程 Linux 服务器?

我可以直接给你针对你项目的测试命令

0