API开发工具 OpenAPI 3

1. 简介

  • Swagger 官网 https://swagger.io/
  • OpenAPI 3 https://springdoc.org/

1.1 Swagger 发展史

  • Swagger 1.x 阶段(2011-2014年)
  • Swagger 2.x 阶段(2014-2017年)
  • OpenAPI 阶段(2017-至今)(即 Swagger 3.x)

1.2 工具

  • SpringFox工具是基于 Swagger 2.x 基础上开发的
  • SpringDoc工具是基于OpenAPI 3.0 规范构建的
    • 在Spring Boot 2.4及以上版本中使用 springdoc-openapi-ui 库来集成Swagger 3.x

1.3 依赖包

org.springdocspringdoc-openapi-ui1.7.0

包含:
io.swagger.core.v3:swagger-core:2.2.9
io.swagger.core.v3:swagger-annotations:2.2.9
io.swagger.core.v3:swagger-models:2.2.9

2. OpenAPI 3

# OpenAPI 3
springdoc:
  packages-to-scan: com.example.concrete.starter.controller
  api-docs:
    enabled: true
  swagger-ui:
    enabled: true

2.1 springdoc-openapi core properties

示例URL http://localhost:8080/v3/api-docs

2.2 swagger-ui properties

示例URL http://localhost:8080/swagger-ui/index.html

2.3 Migrating from SpringFox

3. 实战

3.1 OpenAPI3 配置

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;

@Configuration
public class SwaggerOpenApiConfig {

    @Bean
    public OpenAPI customOpenAPI() {

        // 构建API的联系人信息
        Contact contact = new Contact()
                .name("Tinyspot")
                .email("xxxxxx@136.com")
                .url("tinyspot.live");

        // 授权许可信息(license)
        License license = new License()
                .name("Apache 2.0")
                .url("https://www.apache.org/licenses/LICENSE-2.0.html")
                .identifier("Apache-2.0")
                .extensions(new HashMap());

        Info info = new Info()
                .title("OpenAPI 3.0 示例文档")
                .description("文档描述")
                .version("1.0.0")
                .termsOfService("https://example.com/") // Api接口的服务条款地址
                .license(license)
                .contact(contact);

        return new OpenAPI().info(info);
    }
}

会默认读取所有的接口

3.2 接口描述

@RestController
@RequestMapping("/web")
@Tag(name = "基础接口")
public class ConcreteController {

    @Operation(summary = "打招呼", description = "详细描述...")
    @PostMapping("/greet2")
    public UserVO greet2(UserDTO userDTO) {
        return new UserVO(userDTO.getName(), userDTO.getAge());
    }
}

3.3 模型描述

@Data
@NoArgsConstructor
@AllArgsConstructor
@Schema(name = "UserVO", description = "用户信息")
public class UserVO implements Serializable {
    private static final long serialVersionUID = 5274857955858412692L;

    @Schema(name = "name", description = "用户名")
    private String name;

    @Schema(name = "age", description = "年龄")
    private Integer age;
}

【信息由网络或者个人提供,如有涉及版权请联系COOY资源网邮箱处理】

© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容