SwaggerUI实战:优雅发布API文档

Swagger UI 与文档发布的技术实践

Swagger UI 是一个流行的开源工具,用于可视化 RESTful API 文档。通过 Swagger UI,开发者可以直观地查看、测试和调试 API。以下内容将详细介绍如何集成 Swagger UI 并发布 API 文档,包含丰富的代码示例。


集成 Swagger UI 到 Spring Boot 项目

在 Spring Boot 项目中集成 Swagger UI 需要添加相关依赖。以下是一个典型的 Maven 配置示例:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>3.0.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>3.0.0</version>
</dependency>

配置 Swagger 的 Docket Bean 来定义 API 文档的基本信息:

import springfox.documentation.swagger2.annotations.EnableSwagger2;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.spi.DocumentationType;

@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 文档标题")
            .description("API 文档描述")
            .version("1.0")
            .build();
    }
}

启动项目后,访问 http://localhost:8080/swagger-ui.html 即可查看生成的 API 文档。


自定义 Swagger UI 的显示内容

通过注解可以在代码中为 API 添加更详细的描述。以下是一个控制器方法的示例:

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@Api(tags = "用户管理")
@RequestMapping("/api/users")
public class UserController {

    @GetMapping("/{id}")
    @ApiOperation("根据 ID 获取用户信息")
    public ResponseEntity<User> getUser(
        @ApiParam(value = "用户 ID", required = true) @PathVariable Long id) {
        // 实现逻辑
    }
}

Swagger 还支持通过 @ApiModel@ApiModelProperty 注解为数据模型添加描述:

@ApiModel(description = "用户实体")
public class User {

    @ApiModelProperty(value = "用户 ID", example = "1")
    private Long id;

    @ApiModelProperty(value = "用户名", example = "admin")
    private String username;
}


使用 OpenAPI 3.0 规范

Swagger 也支持 OpenAPI 3.0 规范。以下是一个基于 springdoc-openapi 的配置示例:

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-ui</artifactId>
    <version>1.6.0</version>
</dependency>

配置类可以简化为:

import org.springdoc.core.GroupedOpenApi;

@Configuration
public class OpenApiConfig {

    @Bean
    public GroupedOpenApi publicApi() {
        return GroupedOpenApi.builder()
            .group("public")
            .pathsToMatch("/api/**")
            .build();
    }
}

访问 http://localhost:8080/swagger-ui.htmlhttp://localhost:8080/v3/api-docs 查看生成的 OpenAPI 文档。


发布 Swagger 文档到静态站点

如果需要将 Swagger 文档发布为静态站点,可以使用 swagger-codegen 工具生成 HTML 文件。以下是一个命令行示例:

swagger-codegen generate -i http://localhost:8080/v3/api-docs -l html -o ./apidocs

生成的静态文件可以直接部署到任何 Web 服务器(如 Nginx 或 Apache)。


结合 Spring Security 保护 Swagger UI

如果项目使用了 Spring Security,可以通过配置允许访问 Swagger UI:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll()
            .anyRequest().authenticated();
    }
}


总结

Swagger UI 提供了一种高效的方式来生成和发布 API 文档。通过合理的配置和注解,可以生成清晰、易读的文档,并支持在线测试。无论是开发阶段的调试,还是对外发布的文档,Swagger UI 都能满足需求。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值