在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啟動)或刷新瀏覽器頁面。