1. 安装必要工具与环境准备
在Debian系统上,首先需要安装支撑Swagger运行的基础工具。对于基于Node.js的项目,通过以下命令安装Node.js、npm及Swagger相关依赖:
sudo apt update
sudo apt install -y nodejs npm
sudo npm install -g @nestjs/cli swagger-ui-express swagger-jsdoc
对于Java Spring Boot项目,则需安装Java JDK(11及以上)、Maven及Swagger依赖(如springfox-boot-starter)。
2. 集成Swagger到项目框架
根据项目技术栈选择对应的集成方式:
springfox-boot-starter),并在application.yml中启用Swagger UI:springfox:
documentation:
swagger-ui:
enabled: true
@nestjs/swagger(Nest.js)或swagger-ui-express(Express),并在入口文件(如main.ts或app.js)中配置Swagger文档生成器。例如,Nest.js的配置代码:import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const options = new DocumentBuilder()
.setTitle('Debian API')
.setDescription('API for Debian package management')
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('api-docs', app, document); // 文档访问路径为/api-docs
await app.listen(3000);
}
Express项目的配置示例:const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');
const app = express();
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
这一步将Swagger UI集成到项目中,为后续文档生成奠定基础。3. 使用注解/配置定义API文档
通过Swagger注解或配置文件描述API的路径、参数、响应等信息,使文档与代码同步更新:
@Api(描述模块)、@ApiOperation(描述接口功能)、@ApiParam(描述参数)、@ApiResponse(描述响应)等注解。例如:@RestController
@RequestMapping("/api/packages")
@Api(tags = "Debian包管理")
public class PackageController {
@GetMapping("/{name}")
@ApiOperation(value = "获取指定名称的Debian包信息", notes = "根据包名查询版本、依赖等详情")
public ResponseEntity<Package> getPackage(
@PathVariable @ApiParam(value = "包名", required = true) String name) {
// 业务逻辑
}
}
swagger-jsdoc解析注释生成文档,或在swagger.json中手动定义API规范(OpenAPI 3.0格式)。例如:{
"openapi": "3.0.0",
"info": { "title": "Debian API", "version": "1.0.0" },
"paths": {
"/api/packages/{name}": {
"get": {
"summary": "获取Debian包信息",
"parameters": [
{ "name": "name", "in": "path", "required": true, "description": "包名", "schema": { "type": "string" } }
],
"responses": { "200": { "description": "包信息返回成功" } }
}
}
}
}
注解和配置使文档自动生成,避免了手动编写和维护的麻烦。4. 自动生成与查看API文档
启动项目后,Swagger会根据注解或配置文件自动生成交互式API文档。访问对应路径即可查看:
http://localhost:8080/swagger-ui/(若配置了springfox.documentation.swagger-ui.enabled=true);http://localhost:3000/api-docs(若配置了SwaggerModule.setup('api-docs', ...))。5. 测试与调试API
通过Swagger UI的Try it out按钮,输入参数并发送请求,实时查看API响应结果(包括状态码、响应体、响应头)。例如,测试/api/packages/{name}接口时,输入包名(如nginx),点击“Execute”即可获取该包的详细信息。这种方式减少了使用Postman等工具的步骤,提升了测试效率。
6. 保障文档安全与同步
antMatchers("/swagger-ui/**").authenticated()配置认证;