Swagger在Debian上的集成方法主要分為兩類:基于Node.js(適用于JavaScript/Node.js應用)和基于Java(適用于Spring Boot應用)。以下是詳細步驟:
更新系統包列表并安裝Node.js、npm(Node.js包管理器):
sudo apt update && sudo apt upgrade -y
sudo apt install nodejs npm -y
# 驗證安裝
node -v && npm -v # 應輸出版本號(如v18.x.x、9.x.x)
使用npm全局安裝swagger-ui-express
(用于集成Swagger UI到Express應用)和swagger-jsdoc
(用于從代碼注釋生成Swagger文檔):
sudo npm install -g swagger-ui-express swagger-jsdoc
在項目根目錄下創建swagger.json
(或swagger.yaml
),定義API規范。示例如下:
{
"swagger": "2.0",
"info": {
"title": "Sample API",
"description": "A sample API to demonstrate Swagger integration",
"version": "1.0.0"
},
"basePath": "/api",
"paths": {
"/users": {
"get": {
"summary": "List all users",
"responses": {
"200": {
"description": "A list of users"
}
}
}
}
}
}
在Express應用中引入Swagger中間件,將文檔綁定到指定路徑(如/api-docs
):
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs'); // 若使用YAML格式,需安裝:npm install yamljs
const app = express();
// 加載Swagger文檔(支持JSON/YAML)
const swaggerDocument = YAML.load('./swagger.yaml'); // 或 require('./swagger.json')
// 集成Swagger UI到/api-docs路徑
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
// 示例路由
app.get('/api/users', (req, res) => {
res.json([{ id: 1, name: 'John Doe' }]);
});
// 啟動服務器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
console.log(`Swagger UI available at http://localhost:${PORT}/api-docs`);
});
啟動Express應用:
node app.js
打開瀏覽器訪問http://<your-server-ip>:3000/api-docs
,即可看到Swagger UI界面,展示定義的API文檔。
更新系統包列表并安裝Java(OpenJDK 11+)、Maven(Java構建工具):
sudo apt update && sudo apt upgrade -y
sudo apt install openjdk-11-jdk maven -y
# 驗證安裝
java -version # 應輸出Java版本(如11.x.x)
mvn -version # 應輸出Maven版本(如3.x.x)
使用Spring Initializr創建項目,選擇以下依賴:
Spring Boot 3.x
+ Springdoc OpenAPI
,更適配新版Spring Boot)若使用Maven,在pom.xml
中添加以下依賴(以springdoc-openapi
為例,適配Spring Boot 3.x):
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.5.0</version> <!-- 使用最新穩定版本 -->
</dependency>
若使用Gradle,在build.gradle
中添加:
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.5.0'
若使用傳統springfox-swagger
(Spring Boot 2.x),需創建配置類啟用Swagger:
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;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo")) // 替換為你的控制器包路徑
.paths(PathSelectors.any())
.build();
}
}
若使用springdoc-openapi
(推薦,無需額外配置類),默認會自動掃描控制器并生成文檔。
在控制器類中使用Swagger注解描述API(以springdoc-openapi
為例):
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/api")
public class UserController {
@Operation(summary = "Get all users", description = "Returns a list of all users")
@ApiResponse(responseCode = "200", description = "Successful operation")
@GetMapping("/users")
public List<User> getUsers() {
return List.of(new User(1, "John Doe"), new User(2, "Jane Smith"));
}
}
class User {
private int id;
private String name;
// 構造函數、Getter/Setter省略
}
使用Maven啟動應用:
mvn spring-boot:run
啟動后,訪問http://<your-server-ip>:8080/swagger-ui.html
(springfox
)或http://<your-server-ip>:8080/swagger-ui/index.html
(springdoc
),即可查看交互式API文檔。
springdoc-openapi
適配Spring Boot 3.x,springfox
適配Spring Boot 2.x)。securitySchemes
配置API認證(如Bearer Token),限制文檔訪問權限。以上步驟覆蓋了Debian系統上Swagger的主要集成場景,可根據實際技術棧選擇對應方案。