mcpField
S
spring-boot-openapi-documentation

spring-boot-openapi-documentation

github.com/giuseppe-trisciuoglio开发3654.0k 次安装7 周前更新
代码仓库

关于 spring-boot-openapi-documentation

spring-boot-openapi-documentation 是使用 SpringDoc 为 Spring Boot 项目编写 REST API 文档的技能,指导开发者生成 OpenAPI 3.0 规范、配置 Swagger UI,并记录端点、模型和安全要求。

主要功能

  1. 01生成 OpenAPI 3.0 规范
  2. 02配置 Swagger UI
  3. 03使用注解记录端点和模型
  4. 04描述安全方案与要求
  5. 05记录分页和 API 分组
  6. 06补充验证规则与响应详情

适用场景

  1. 01为 Spring Boot 项目添加 API 文档
  2. 02描述请求和响应模型
  3. 03记录 JWT 或 OAuth2 安全配置
  4. 04在 Swagger UI 中检查 API 文档

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill spring-boot-openapi-documentation

安装后在 Claude Code 中输入/spring-boot-openapi-documentation确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
advanced-configuration.md
annotations-reference.md
build-integration.md
complete-examples.md
configuration.md
controller-documentation.md
dependency-setup.md
exception-handling.md
model-documentation.md
pagination-support.md
security-configuration.md
springdoc-official.md
troubleshooting.md

详细介绍

使用 SpringDoc 的 Spring Boot OpenAPI 文档

概述

SpringDoc OpenAPI 可自动为 Spring Boot 项目生成 OpenAPI 3.0 文档,并提供 Swagger UI Web 界面,方便浏览和测试 API。

适用场景

  • 在 Spring Boot 3.x 项目中配置 SpringDoc OpenAPI
  • 为 REST API 生成 OpenAPI 3.0 规范
  • 配置和自定义 Swagger UI
  • 使用注解添加详细的 API 文档
  • 为请求/响应模型添加带验证的文档
  • 编写 API 安全文档(JWT、OAuth2、Basic Auth)
  • 编写支持分页和排序的端点文档
  • 为 API 端点添加示例和架构
  • 以编程方式自定义 OpenAPI 定义
  • 支持多个 API 分组和版本
  • 编写错误响应和异常处理器的文档
  • 在 API 文档中添加 JSR-303 Bean Validation
  • 支持基于 Kotlin 的 Spring Boot API

快速参考

概念描述
依赖项WebMvc 使用 springdoc-openapi-starter-webmvc-ui,WebFlux 使用 springdoc-openapi-starter-webflux-ui
配置使用 springdoc.api-docs.* 和 springdoc.swagger-ui.* 属性配置 application.yml
访问入口OpenAPI JSON:/v3/api-docs,Swagger UI:/swagger-ui/index.html
核心注解@Tag、@Operation、@ApiResponse、@Parameter、@Schema、@SecurityRequirement
安全性在 OpenAPI Bean 中配置安全方案,并通过 @SecurityRequirement 应用
分页将 @ParameterObject 与 Spring Data Pageable 搭配使用

说明

1. 添加依赖项

根据应用类型(WebMvc 或 WebFlux)添加 SpringDoc starter。Maven/Gradle 配置请参见 dependency-setup.md。

2. 配置 SpringDoc

在 application.yml 中设置基本配置:

springdoc:
  api-docs:
    path: /api-docs
  swagger-ui:
    path: /swagger-ui.html
    operationsSorter: method

高级选项请参见 configuration.md。

3. 编写控制器文档

使用 OpenAPI 注解添加描述性信息:

@RestController
@Tag(name = "Book", description = "Book management APIs")
public class BookController {

    @Operation(summary = "Get book by ID")
    @ApiResponse(responseCode = "200", description = "Book found")
    @GetMapping("/{id}")
    public Book findById(@PathVariable Long id) { }
}

相关模式请参见 controller-documentation.md。

4. 编写模型文档

为 DTO 添加 @Schema 注解:

@Schema(description = "Book entity")
public class Book {
    @Schema(example = "1", accessMode = Schema.AccessMode.READ_ONLY)
    private Long id;

    @Schema(example = "Clean Code", required = true)
    private String title;
}

验证模式请参见 model-documentation.md。

5. 配置安全性

在 OpenAPI Bean 中设置安全方案:

@Bean
public OpenAPI customOpenAPI() {
    return new OpenAPI()
        .components(new Components()
            .addSecuritySchemes("bearer-jwt", new SecurityScheme()
                .type(SecurityScheme.Type.HTTP)
                .scheme("bearer")
                .bearerFormat("JWT")
            )
        );
}

在控制器上使用 @SecurityRequirement(name = "bearer-jwt") 应用。请参见 security-configuration.md。

6. 编写分页文档

对 Spring Data Pageable 使用 @ParameterObject:

@GetMapping("/paginated")
public Page<Book> findAll(@ParameterObject Pageable pageable) {
    return repository.findAll(pageable);
}

请参见 pagination-support.md。

7. 测试文档

访问 /swagger-ui/index.html 中的 Swagger UI,检查文档是否完整。

8. 面向生产环境进行自定义

配置 API 分组、版本控制和构建插件。请参见 advanced-configuration.md 和 build-integration.md。

最佳实践

  • 使用描述性操作摘要:简短(< 120 个字符)、清晰明了
  • 记录所有响应代码:包括成功(2xx)、客户端错误(4xx)和服务器错误(5xx)
  • 为请求/响应正文添加示例:使用 @ExampleObject 提供贴近实际的示例
  • 充分利用 JSR-303 验证注解:SpringDoc 会根据验证注解自动生成约束
  • 对复杂参数使用 @ParameterObject:尤其适用于 Pageable 和自定义筛选对象
  • 使用 @Tag 对相关端点分组:按领域实体或功能组织 API
  • 记录安全要求:在需要身份验证的位置应用 @SecurityRequirement
  • 适当隐藏内部端点:使用 @Hidden 或创建单独的 API 分组
  • 自定义 Swagger UI 以改善用户体验:启用筛选、排序和试用功能
  • 为 API 文档设置版本:在 OpenAPI Info 中包含版本信息

参考资料

限制与警告

  • 不要在 API 示例或架构描述中泄露敏感数据
  • 尽量精简 OpenAPI 注解,避免控制器代码过于杂乱;尽可能使用全局配置
  • 大型 API 定义可能影响 Swagger UI 的性能;请考虑按领域对 API 分组
  • 架构生成可能无法正确处理复杂泛型;请使用显式的 @Schema 注解
  • 避免 DTO 中出现循环引用,因为这会导致架构生成时无限递归
  • 使用 @SecurityRequirement 注解前,必须正确配置安全方案
  • 隐藏端点(@Operation(hidden = true))仍会在代码中显示,也可能通过其他文档工具泄露

示例

基本控制器文档
@RestController
@Tag(name = "Books", description = "Book management APIs")
@RequestMapping("/api/books")
public class BookController {

    @Operation(
        summary = "Get book by ID",
        description = "Retrieves detailed information about a specific book"
    )
    @ApiResponse(responseCode = "200", description = "Book found")
    @ApiResponse(responseCode = "404", description = "Book not found")
    @GetMapping("/{id}")
    public Book getBook(@PathVariable Long id) {
        return bookService.findById(id);
    }

    @Operation(summary = "Create new book")
    @SecurityRequirement(name = "bearer-jwt")
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public Book createBook(@Valid @RequestBody CreateBookRequest request) {
        return bookService.create(request);
    }
}
带验证的模型文档
@Schema(description = "Book entity")
public class Book {
    @Schema(description = "Unique identifier", example = "1", accessMode = Schema.AccessMode.READ_ONLY)
    private Long id;

    @Schema(description = "Book title", example = "Clean Code", required = true)
    @NotBlank
    @Size(min = 1, max = 200)
    private String title;

    @Schema(description = "Author name", example = "Robert C. Martin")
    @NotBlank
    private String author;

    @Schema(description = "Price in USD", example = "29.99", minimum = "0")
    @NotNull
    @DecimalMin("0.0")
    private BigDecimal price;
}
安全配置
@Bean
public OpenAPI customOpenAPI() {
    return new OpenAPI()
        .info(new Info()
            .title("Book API")
            .version("1.0.0")
            .description("REST API for book management"))
        .components(new Components()
            .addSecuritySchemes("bearer-jwt", new SecurityScheme()
                .type(SecurityScheme.Type.HTTP)
                .scheme("bearer")
                .bearerFormat("JWT"))
            .addSecuritySchemes("api-key", new SecurityScheme()
                .type(SecurityScheme.Type.APIKEY)
                .in(SecurityScheme.In.HEADER)
                .name("X-API-Key")));
}

相关技能

  • spring-boot-rest-api-standards — REST API 设计规范
  • spring-boot-dependency-injection — 依赖注入模式
  • unit-test-controller-layer — REST 控制器测试
  • spring-boot-actuator — 生产环境监控和管理

外部资源

评论

支持 Markdown