Swagger:接口信息管理

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

主要功能

  • 支持 API 自动生成同步的在线文档使用 Swagger 后可以直接通过代码生成文档不再需要自己手动编写接口文档

  • 提供 Web 页面在线测试 API

导入依赖

Swagger 与Spring框架Spring-fox相结合

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

SpringBoot 2.6以上版本修改了路径匹配规则但是Swagger3还不支持所以要修改配置

spring:
    mvc:
        pathmatch:
      matching-strategy: ant_path_matcher

项目启动后可以直接打开http://localhost:8080/swagger-ui/index.htmlUI界面可以支持第三方

页面信息配置

直接使用配置类配置

@Configuration
public class SwaggerConfiguration {

    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.OAS_30).apiInfo(
                new ApiInfoBuilder()
                        .contact(new Contact("名字", "网址", "邮箱"))
                        .title("*** - 在线API接口文档")
                        .build()
        );
    }
}

接口信息配置

不需要显示ErrorController相关的API需要在配置类中选择需要扫面的包

@Bean
public Docket docket() {
    ApiInfo info = new ApiInfoBuilder()
            .contact(new Contact("名字", "网址", "邮箱"))
            .title("*** - 在线API接口文档")
            .build()
    return new Docket(DocumentationType.OAS_30)
            .apiInfo(info)
            .select()       //对项目中的所有API接口进行选择
            .apis(RequestHandlerSelectors.basePackage("com.example.controller"))//通过包名做API的选择
            .build();
}

为一个Controller编写API描述信息

@Api(tags = "验证接口", description = "包括用户登录、注册、验证码请求等")
@RestController
@RequestMapping("/api/auth")
public class AuthApiController {

为请求映射配置描述信息

@ApiResponses({
        @ApiResponse(code = 200, message = "邮件发送成功"),  
        @ApiResponse(code = 500, message = "邮件发送失败")   //不同返回状态码描述
})
@ApiOperation("请求邮件验证码")   //接口描述
@GetMapping("/verify-code")
public RestBean<Void> verifyCode(@ApiParam("邮箱地址")   //请求参数的描述
                                 @RequestParam("email") String email){
@ApiIgnore     //忽略此请求映射
@PostMapping("/login-success")
public RestBean<Void> loginSuccess(){
    return new RestBean<>(200, "登陆成功");
}

为实体类配置相关的描述信息

@ApiModel(description = "响应实体封装类")
public class RestBean<T> {
阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6