OpenAPI (Swagger) 规范:接口文档自动化实战
Lisa Tan | 2026-08-27T20:55:14 | Spring Boot, DevOps
用 OpenAPI 3.0 规范定义 REST API,配合 SpringDoc 自动生成交互式文档,并集成到 CI 流程进行契约测试。
# OpenAPI (Swagger) 规范实战 ## 什么是 OpenAPI? OpenAPI(前身是 Swagger)是 REST API 的标准描述规范,用 YAML/JSON 格式描述接口的路径、参数、响应和安全策略。 ## Spring Boot 集成 SpringDoc ```xml org.springdoc springdoc-openapi-starter-webmvc-ui 2.3.0 ``` ```yaml # application.yml springdoc: api-docs: path: /v3/api-docs swagger-ui: path: /swagger-ui.html tags-sorter: alpha operations-sorter: method ``` ## 注解使用 ```java @RestController @RequestMapping("/api/posts") @Tag(name = "文章管理", description = "博客文章的 CRUD 接口") public class PostController { @Operation( summary = "创建文章", description = "创建新的博客文章,需要登录" ) @ApiResponses({ @ApiResponse(responseCode = "201", description = "创建成功"), @ApiResponse(responseCode = "400", description = "参数校验失败"), @ApiResponse(responseCode = "401", description = "未登录"), }) @PostMapping public ResponseEntity createPost( @RequestBody @Valid PostCreateDTO dto) { return ResponseEntity.status(201).body(postService.create(dto)); } @Operation(summary = "分页查询文章") @GetMapping public PageResult listPosts( @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") int page, @Parameter(description = "每页条数", example = "10") @RequestParam(defaultValue = "10") int size, @Parameter(description = "搜索关键词") @RequestParam(required = false) String keyword) { return postService.list(page, size, keyword); } } ``` ## DTO 模型注解 ```java @Schema(description = "文章创建请求") public class PostCreateDTO { @Schema(description = "文章标题", example = "Spring Boot 入门", requiredMode = Schema.RequiredMode.REQUIRED, maxLength = 200) @NotBlank @Size(max = 200) private String title; @Schema(description = "文章内容", example = "正文内容...", requiredMode = Schema.RequiredMode.REQUIRED) @NotBlank private String content; @Schema(description = "标签 ID 列表", example = "[1, 3, 5]") private List tagIds; } ``` ## 安全配置 ```java @Configuration public class OpenApiConfig { @Bean public OpenAPI customOpenAPI() { return new OpenAPI() .info(new Info() .title("Blog API") .version("1.0") .description("博客社区接口文档")) .addSecurityItem(new SecurityRequirement().addList("Bearer")) .components(new Components() .addSecuritySchemes("Bearer", new SecurityScheme() .type(SecurityScheme.Type.HTTP) .scheme("bearer") .bearerFormat("JWT"))); } } ``` ## 导出 API 文档 ```bash # 导出 JSON curl http://localhost:8080/v3/api-docs > api-docs.json # 导出 YAML curl http://localhost:8080/v3/api-docs.yaml > api-docs.yaml # 用 openapi-generator 生成客户端 SDK npx openapi-generator-cli generate \ -i api-docs.json \ -g typescript-axios \ -o src/api ``` ## CI 契约测试 ```yaml # GitHub Actions - name: API Docs Diff run: | curl http://localhost:8080/v3/api-docs > new-api-docs.json diff api-docs.json new-api-docs.json || echo "API has changed!" ``` ## 最佳实践 1. 所有接口都加 `@Operation` 注解 2. DTO 字段加 `@Schema` 和验证注解 3. 生成的文档提交到 Git,CI 中检测变更 4. 前后端基于同一份 OpenAPI 文档开发,减少沟通成本