Swagger 高级功能
Swagger(现称 OpenAPI)是用于设计、构建和记录 RESTful API 的强大工具。除了基础的 API 文档生成功能,Swagger 还提供了许多高级功能,能够提升开发效率和文档的可读性。以下是几个关键的高级功能及其代码示例。
动态 API 文档生成
通过集成 Swagger UI,可以动态生成 API 文档,并在运行时更新。以下是一个 Spring Boot 示例:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("API Documentation")
.description("Sample REST API")
.version("1.0")
.build();
}
}
访问 /swagger-ui.html 即可查看生成的文档。
自定义响应模型
Swagger 允许定义复杂的响应模型,并自动生成示例。以下是一个带有自定义响应的示例:
@ApiOperation(value = "获取用户信息", response = UserResponse.class)
@GetMapping("/users/{id}")
public ResponseEntity<UserResponse> getUser(@PathVariable Long id) {
UserResponse user = userService.findById(id);
return ResponseEntity.ok(user);
}
对应的响应模型:
@ApiModel(description = "用户信息响应")
public class UserResponse {
@ApiModelProperty(value = "用户 ID", example = "1")
private Long id;
@ApiModelProperty(value = "用户名", example = "admin")
private String username;
// Getters and setters
}
OAuth2 集成
Swagger 支持 OAuth2 认证,可直接在 UI 界面进行授权测试:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
.paths(PathSelectors.any())
.build()
.securitySchemes(Arrays.asList(securityScheme()))
.securityContexts(Arrays.asList(securityContext()));
}
private SecurityScheme securityScheme() {
return new OAuthBuilder()
.name("oauth2")
.grantTypes(Arrays.asList(new AuthorizationCodeGrant(
new TokenRequestEndpoint("/oauth2/authorize", "client-id", "client-secret"),
new TokenEndpoint("/oauth2/token", "access-token")
)))
.build();
}
private SecurityContext securityContext() {
return SecurityContext.builder()
.securityReferences(Arrays.asList(new SecurityReference("oauth2", new AuthorizationScope[0])))
.build();
}
}
分组 API 文档
在大型项目中,可能需要按模块分组 API 文档:
@Bean
public Docket userApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("user")
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.user"))
.paths(PathSelectors.any())
.build();
}
@Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("product")
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.product"))
.paths(PathSelectors.any())
.build();
}
自定义注解扩展
Swagger 支持自定义注解,增强文档的可读性:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface ApiFileUpload {
String value() default "文件上传";
}
@ApiFileUpload("上传文件")
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
return ResponseEntity.ok("File uploaded");
}
这些高级功能可以大幅提升 API 的可维护性和开发体验。通过灵活运用 Swagger,可以生成更具表现力的 API 文档,并简化测试和调试流程。
4507

被折叠的 条评论
为什么被折叠?



