温馨提示×

如何调试linux swagger

小樊
38
2026-09-03 13:09:05
栏目: 智能运维

在 Linux 环境下“调试 Swagger”通常涉及几种不同场景:

  • 调试 Swagger UI / Swagger Editor(前端页面)
  • 调试 后端 Swagger 接口文档生成(如 Springfox、springdoc、FastAPI、Go Swagger 等)
  • 调试 Swagger 接口调用失败(404 / 500 / 权限等问题)

下面按常见场景给你一套可落地的调试思路


一、确认 Swagger 是否正常启动

1. 查看进程与端口

ps -ef | grep swagger
netstat -tunlp | grep 8080
# 或
ss -tunlp | grep 8080

2. 本机访问测试

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

如果是远程服务器:

curl http://<服务器IP>:端口/swagger-ui.html

二、调试 Swagger UI 打不开

常见原因

  • 路径错误
  • 被 Spring Security / Nginx 拦截
  • 前端静态资源 404

检查项

Spring Boot 示例

spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

安全框架放行

@Override
public void configure(WebSecurity web) {
    web.ignoring().antMatchers(
        "/swagger-ui.html",
        "/swagger-ui/**",
        "/v3/api-docs/**",
        "/webjars/**"
    );
}

Nginx 示例

location /swagger-ui/ {
    proxy_pass http://backend/swagger-ui/;
}

三、调试接口文档不显示 / 为空

1. 打开浏览器开发者工具(F12)

重点看:

  • Network → /v3/api-docs
  • Console 是否有 JS 报错

2. 直接访问 API Docs

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

如果返回为空 {}

  • 注解未加(@RestController / @Operation
  • 扫描包路径错误

Spring Boot 示例

@SpringBootApplication
@OpenAPIDefinition(info = @Info(title = "API", version = "1.0"))
public class App {}

四、调试 Swagger 接口调用失败

1. 看后端日志

journalctl -u your-service
# 或
tail -f logs/app.log

2. 使用 curl 模拟 Swagger 请求

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

3. 常见问题

  • 参数名不一致(@RequestParam vs @RequestBody
  • 鉴权失败(Token 未填)
  • CORS 跨域

五、调试 Swagger 生成代码(Swagger Codegen)

生成命令

swagger-codegen generate \
  -i api.yaml \
  -l java \
  -o out/

调试技巧

swagger-codegen validate -i api.yaml

六、推荐调试组合拳

# 1. 看端口
ss -tunlp

# 2. 看接口
curl http://localhost:8080/v3/api-docs

# 3. 看日志
tail -f app.log

# 4. 浏览器 F12

七、如果你愿意,我可以更精准帮你

你可以补充:

  1. 使用的技术栈(Spring Boot / FastAPI / Go / Node)
  2. Swagger 版本(2.x / 3.x / OpenAPI 3)
  3. 具体现象(打不开 / 没接口 / 调用报错)

我可以直接给你对应配置文件和排错命令

0