一、准备工作:安装必要工具 在Linux系统上自定义Swagger文档前,需根据技术栈安装对应工具。若使用Node.js(Express/Koa),通过npm安装核心工具:
npm install swagger-jsdoc swagger-ui-express --save-dev # 生成和展示Swagger文档
若使用Java(Spring Boot),添加Swagger依赖到pom.xml(Springfox)或build.gradle(SpringDoc OpenAPI):
<!-- SpringFox(Swagger 2) -->
<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>
// SpringDoc OpenAPI(推荐,支持OpenAPI 3)
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.5.0'
安装完成后,确保工具版本与项目技术栈兼容。
二、编写Swagger配置文件(定义文档结构)
Swagger文档的核心是OpenAPI规范(YAML/JSON格式),需创建swagger.yaml或swagger.json文件(推荐YAML,可读性更强)。以下是关键配置项:
/api/users)、HTTP方法(GET/POST)、参数(路径/查询/请求体)、响应(状态码、数据结构);User对象)、参数、响应(减少重复配置)。示例(YAML格式,适用于Spring Boot/Node.js):
openapi: 3.0.0
info:
title: "用户管理API"
description: "提供用户信息的增删改查接口"
version: "1.0.0"
contact:
name: "开发团队"
email: "dev@example.com"
servers:
- url: "http://localhost:8080" # 开发环境
description: "本地开发服务器"
paths:
/api/users:
get:
summary: "获取用户列表"
description: "返回所有用户的简要信息"
responses:
'200':
description: "成功返回用户列表"
content:
application/json:
schema:
type: array
items:
$ref: "#/components/schemas/User"
components:
schemas:
User:
type: object
properties:
id:
type: integer
description: "用户唯一ID"
name:
type: string
description: "用户姓名"
required:
- id
- name
配置文件需放在项目根目录或指定路径(如Spring Boot的src/main/resources)。
三、集成Swagger到应用(连接文档与代码)
在Express应用中,通过swagger-ui-express中间件加载Swagger文档:
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.yaml'); // 导入配置文件
const app = express();
const PORT = process.env.PORT || 3000;
// 集成Swagger UI(挂载到/api-docs路径)
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
// 示例API路由(需与swagger.yaml中的路径一致)
app.get('/api/users', (req, res) => {
res.json([{ id: 1, name: '张三' }, { id: 2, name: '李四' }]);
});
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
启动应用后,访问http://localhost:3000/api-docs即可查看Swagger UI界面。
创建配置类,启用Swagger并配置扫描路径:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
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()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("用户管理API")
.description("提供用户信息的增删改查接口")
.version("1.0.0")
.build();
}
}
访问http://localhost:8080/swagger-ui.html查看文档。
无需额外配置类,只需添加依赖,Spring Boot会自动识别swagger.yaml文件。访问http://localhost:8080/swagger-ui/index.html即可查看文档。
四、自定义Swagger文档(优化可读性与功能)
通过配置文件调整标题、描述、版本等信息,使文档更符合项目需求(如上述swagger.yaml中的info部分)。
swagger-ui-express的customCss选项引入自定义CSS:app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, {
customCss: '.swagger-ui .topbar { background-color: #4CAF50; }' // 修改顶部栏颜色
}));
Docket配置自定义CSS或Logo:@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.enableUrlTemplating(true)
.uiConfiguration(uiConfig -> uiConfig
.deepLinking(true)
.displayOperationId(false)
.defaultModelsExpandDepth(3)
.defaultModelExpandDepth(3)
.defaultModelRendering(ModelRendering.EXAMPLE)
.displayRequestDuration(true)
.docExpansion(DocExpansion.NONE)
.filter(false)
.maxDisplayedTags(null)
.operationsSorter(OperationsSorter.ALPHA)
.showExtensions(false)
.tagsSorter(TagsSorter.ALPHA)
.supportedSubmitMethods(UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS)
)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
.paths(PathSelectors.any())
.build();
}
或通过application.properties添加自定义Logo:springfox.documentation.swagger.v2.path=/swagger-resources/v2/api-docs
springfox.documentation.swagger-ui.custom-css-url=/custom.css
springfox.documentation.swagger-ui.logo-image=/logo.png
@ApiIgnore注解隐藏特定接口或参数:@ApiIgnore
@GetMapping("/admin/secret")
public String secret() {
return "This is a secret endpoint";
}
swagger.yaml中通过x-hidden: true标记隐藏路径:/api/admin/secret:
x-hidden: true # 不显示在Swagger UI中
get:
summary: "敏感接口"
responses:
'200':
description: "隐藏的接口内容"
在代码中使用Swagger注解(Java)或YAML描述(Node.js),丰富接口信息:
@ApiOperation(value = "获取用户信息", notes = "根据用户ID获取详细信息,需管理员权限")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "成功获取用户信息", response = User.class),
@ApiResponse(code = 404, message = "用户不存在")
})
@GetMapping("/api/users/{id}")
public ResponseEntity<User> getUser(@ApiParam(value = "用户ID", required = true, example = "1") @PathVariable Integer id) {
// 实现逻辑
}
/api/users/{id}:
get:
summary: "获取用户信息"
description: "根据用户ID获取详细信息,需管理员权限"
parameters:
- in: path
name: id
required: true
schema:
type: integer
description: "用户唯一ID"
responses:
'200':
description: "成功获取用户信息"
content:
application/json:
schema:
$ref: "#/components/schemas/User"
example:
id: 1
name: "张三"
'404':
description: "用户不存在"
tags属性分组接口:@ApiOperation(value = "用户登录", tags = {"用户认证"})
@PostMapping("/api/login")
public ResponseEntity<String> login() {
// 实现逻辑
}
tags字段分组:/api/users/login:
post:
tags: ["用户认证"] # 归类到“用户认证”分组
summary: "用户登录"
# ...
五、验证与优化
swagger.yaml是否符合OpenAPI规范;PathSelectors.ant()过滤路径,减少扫描范围(如仅扫描/api/v1/*)。