温馨提示×

Debian下Swagger怎么测试

小樊
40
2026-08-14 05:34:25
栏目: 智能运维

在 Debian 下测试 Swagger(OpenAPI) 接口,常见有 Swagger UI、curl、Postman、命令行工具 等方式。下面按最常用场景给你一个完整说明。


一、确认 Swagger/OpenAPI 接口是否可用

一般 Swagger 提供以下地址之一:

http://localhost:8080/swagger-ui.html
http://localhost:8080/swagger-ui/
http://localhost:8080/api-docs
http://localhost:8080/v3/api-docs

✅ 先确认接口是否可访问:

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

如果有 JSON 返回,说明 Swagger 接口正常。


二、使用 Swagger UI 测试(最推荐)

1️⃣ 浏览器访问 Swagger UI

在 Debian 桌面或转发端口后访问:

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

或:

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

✅ 在页面中:

  • 展开接口
  • 点击 Try it out
  • 填写参数
  • 点击 Execute

2️⃣ 如果服务器没有桌面(服务器环境)

✅ 方法一:本地端口转发(推荐)

在本地电脑执行:

ssh -L 8080:localhost:8080 user@debian-server

然后本地浏览器访问:

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

三、直接用 curl 测试 Swagger 接口(服务器常用)

1️⃣ GET 接口

curl http://localhost:8080/api/users

2️⃣ POST + JSON

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

3️⃣ 带 Token(JWT)

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

四、使用 Swagger Codegen / OpenAPI Generator(进阶)

安装 openapi-generator

sudo apt install openapi-generator

生成客户端(如 Java / Python)

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

五、使用 Postman 测试(图形化)

  1. 打开 Postman
  2. Import → Link
  3. 输入:
http://localhost:8080/v3/api-docs
  1. Postman 会自动生成所有接口

✅ 适合复杂参数、Header、Auth 测试


六、常见问题排查

❌ 访问不了 swagger-ui

检查:

  • 服务是否启动
  • 端口是否开放
  • 是否被 Spring Security 拦截

Spring Boot 示例放行:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
      .authorizeHttpRequests(auth -> auth
        .requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll()
        .anyRequest().authenticated()
      );
    return http.build();
}

❌ curl 返回 403 / 401

说明接口需要认证:

  • JWT
  • Basic Auth
  • Cookie

七、总结(推荐组合)

场景 推荐方式
本地开发 Swagger UI
服务器 curl + SSH 端口转发
自动化 openapi-generator
复杂测试 Postman

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

  • ✅ 是 Spring Boot / Node / Python / Go
  • ✅ Swagger 版本(2.x 还是 3.x)?
  • ✅ 是否 403 / 404?

我可以给你针对你项目的精确测试方案

0