在Linux上使用Swagger进行API调试前,需先安装Node.js(提供npm包管理器)和Docker(可选,用于快速部署Swagger Editor/UI)。
sudo apt update && sudo apt install -y nodejs npm
docker
命令可用。sudo npm install -g swagger-editor
sudo npm install -g swagger-ui
swagger-editor
,默认访问http://localhost:9000
;swagger-ui
,默认访问http://localhost:8080
。docker pull swaggerapi/swagger-editor:v4.6.0
docker run -d -p 38080:8080 --name swagger-editor swaggerapi/swagger-editor:v4.6.0
docker pull swaggerapi/swagger-ui:v4.15.5
docker run -d -p 38081:8080 --name swagger-ui swaggerapi/swagger-ui:v4.15.5
http://<Linux服务器IP>:38080
;http://<Linux服务器IP>:38081
。创建swagger.yaml
(或swagger.json
)文件,定义API的基本信息、路径、参数、响应等。示例如下:
swagger: '2.0' info: title: Linux API调试示例 version: 1.0.0 description: 用于演示Linux环境下Swagger调试的API basePath: /api/v1 schemes: - http paths: /user/{id}: get: summary: 根据用户ID获取用户信息 description: 返回指定ID的用户详情 parameters: - name: id in: path required: true type: integer description: 用户唯一标识 responses: '200': description: 成功获取用户信息 schema: type: object properties: id: type: integer name: type: string '404': description: 用户不存在
若使用Spring Boot框架,可通过依赖和配置自动生成Swagger文档:
pom.xml
):<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; @Configuration public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.example.controller")) // 替换为你的Controller包路径 .paths(PathSelectors.any()) .build(); } }
http://<服务器IP>:8080/swagger-ui.html
(Spring Boot默认端口)即可查看文档。http://localhost:9000
(本地)或http://<服务器IP>:38080
(远程),在线编写/修改swagger.yaml
文件;http://localhost:8080
(本地)或http://<服务器IP>:38081
(远程),加载swagger.yaml
文件;/user/{id}/get
),填写路径参数(如id: 1
);若不想用Swagger UI,可通过curl命令直接测试接口:
curl -X GET "http://<服务器IP>:8080/api/v1/user/1"
curl -X POST "http://<服务器IP>:8080/api/v1/user/create" \ -H "Content-Type: application/json" \ -d '{"name": "John Doe", "age": 30}'
curl -X POST "http://<服务器IP>:8080/api/v1/user/login" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "username=admin&password=123456"
curl -X POST "http://<服务器IP>:8080/api/v1/upload" \ -F "file=@/path/to/local/file.txt" \ -F "description=Test file"
-p
参数修改映射端口(如docker run -d -p 4000:8080
);@CrossOrigin
注解);swagger.yaml
后,需重启Swagger UI服务(若通过swagger serve
启动)或刷新浏览器页面。