Linux环境下Swagger进行API测试与调试的完整流程
在Linux系统中,可通过以下方式安装Swagger工具,满足不同场景需求:
docker pull swaggerapi/swagger-editor:v4.6.0
;运行:docker run -d -p 38080:8080 swaggerapi/swagger-editor:v4.6.0
,访问http://localhost:38080
即可使用。docker pull swaggerapi/swagger-ui:v4.15.5
;运行:docker run -d -p 38081:8080 swaggerapi/swagger-ui:v4.15.5
,访问http://localhost:38081
查看文档。npm install -g swagger-jsdoc swagger-ui-express
(用于生成文档)或npm install -g swagger
(用于命令行操作)。Swagger的核心是OpenAPI规范文件(swagger.yaml
或swagger.json
),需定义API的基本信息、端点、参数及响应规则。
示例swagger.yaml
结构:
swagger: "2.0"
info:
title: Sample API
version: 1.0.0
paths:
/users:
get:
summary: Get all users
parameters:
- name: limit
in: query
type: integer
default: 10
responses:
200:
description: A list of users
schema:
type: array
items:
$ref: "#/definitions/User"
definitions:
User:
type: object
properties:
id:
type: integer
name:
type: string
将文件放置在项目根目录,作为后续测试的依据。
-v $(pwd)/swagger.yaml:/app/swagger.yaml
);springdoc-openapi
自动生成文档并启动Swagger UI。<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.5.0</version>
</dependency>
配置路径:src/main/resources/application.yml
中添加:springdoc:
api-docs:
path: /v3/api-docs
swagger-ui:
path: /swagger-ui.html
启动应用后,访问http://localhost:8080/swagger-ui.html
即可查看文档。Swagger UI提供了可视化测试界面,无需编写代码即可快速验证API:
http://localhost:38081
),找到目标接口(如/users
);limit=5
);若需要批量或脚本化测试,可使用Swagger命令行工具(如swagger-jsdoc
+swagger-ui-express
):
swagger generate spec -o swagger.json
,生成swagger.json
文件;swagger serve --no-open swagger.json
启动本地Swagger UI服务;swagger.json
→点击接口右侧的绿色三角按钮发送请求。curl "http://localhost:8080/users?limit=5"
;curl -X POST http://localhost:8080/users -H "Content-Type: application/json" -d '{"name":"John"}'
。logs/application.log
),定位错误原因(如空指针、数据库连接失败);通过以上步骤,可在Linux环境下高效使用Swagger进行API测试与调试,覆盖从手动验证到自动化测试的全流程需求。