快速上手SwaggerUI:API文档神器

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

Swagger UI 简介

Swagger UI 是一个用于可视化 RESTful API 文档的工具,基于 OpenAPI 规范。它通过交互式界面展示 API 的端点、参数、请求示例和响应结构,极大提升了开发者和用户的体验。

集成 Swagger UI 到 Spring Boot 项目

在 Spring Boot 项目中集成 Swagger UI 通常使用 springfox-swagger2springfox-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

创建一个配置类 SwaggerConfig,用于定义 Swagger 的基本信息:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
}

自定义 Swagger 文档信息

可以通过 Docket 对象自定义文档的标题、描述、版本等信息:

@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
            .paths(PathSelectors.any())
            .build();
}

private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
            .title("API 文档标题")
            .description("API 文档描述")
            .version("1.0")
            .build();
}

使用 Swagger 注解

在控制器和方法上使用 Swagger 注解可以增强文档的可读性。以下是一个示例:

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

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

    @GetMapping("/user/{id}")
    @ApiOperation("根据 ID 获取用户信息")
    public User getUser(
            @ApiParam(value = "用户 ID", required = true)
            @PathVariable Long id) {
        return new User(id, "张三");
    }

    @PostMapping("/user")
    @ApiOperation("创建用户")
    public User createUser(
            @ApiParam(value = "用户信息", required = true)
            @RequestBody User user) {
        return user;
    }
}

class User {
    private Long id;
    private String name;

    // 构造方法、Getter 和 Setter 省略
}

访问 Swagger UI

启动项目后,访问 http://localhost:8080/swagger-ui.html 即可看到 Swagger UI 界面。界面中会展示所有 API 的详细信息,包括请求方法、参数和响应示例。

生成 OpenAPI 规范文件

Swagger 支持生成 OpenAPI 规范文件(通常是 JSON 或 YAML 格式),可以用于其他工具或平台。通过访问 http://localhost:8080/v2/api-docs 可以获取 JSON 格式的 OpenAPI 规范。

发布文档到静态站点

生成的 OpenAPI 规范文件可以用于构建静态文档站点。例如,使用 redoc-cli 工具:

npx redoc-cli bundle api-docs.json -o index.html

这将生成一个 index.html 文件,可以直接部署到任何静态站点托管服务(如 GitHub Pages 或 Netlify)。

使用 Swagger UI 的进阶配置

Swagger UI 支持多种自定义配置,例如修改主题、隐藏某些端点或添加认证信息。以下是一个自定义配置的示例:

@Bean
public UiConfiguration uiConfig() {
    return UiConfigurationBuilder.builder()
            .deepLinking(true)
            .displayOperationId(false)
            .defaultModelsExpandDepth(1)
            .defaultModelExpandDepth(1)
            .defaultModelRendering(ModelRendering.EXAMPLE)
            .displayRequestDuration(false)
            .docExpansion(DocExpansion.NONE)
            .filter(false)
            .maxDisplayedTags(null)
            .operationsSorter(OperationsSorter.ALPHA)
            .showExtensions(false)
            .tagsSorter(TagsSorter.ALPHA)
            .validatorUrl(null)
            .build();
}

总结

Swagger UI 是一个功能强大的 API 文档工具,通过简单的配置和注解即可生成交互式文档。结合 OpenAPI 规范,可以进一步将文档发布为静态站点,方便团队协作和对外共享。

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值