统一的API接口平台
有了统一的API接口平台,不管对内还是对外,都能更好做到:统一接口开发、统一接口管理、统一接口开放服务。
统一接口开发:包括API接口的命名、分类、格式、接口文档、接口变更记录、接口发布、接口测试、接口日记等,都要统一风格、规范标准和约束。
统一接口管理:包括API接口的升级、增加参数、部署、性能监控、错误日志,同时结合开发、测试、运维、文档等形成整套的研发体系和闭环。
统一接口开放服务:主要是针对接口的IP白名单、接口申请、接口调用权限、接口次数限制、接口流量统计,以及开发者账号的开通注册,以应用的创建和审核。解决要不要对接口收费,怎么收费和进行服务、售后支持。
概念认知
Swagger:是一种用于描述RESTFUL API的规范,它提供了一种简单的来描述API的请求和相应参数、错误码、返回数据类型等信息,是开发者可以方便了解API使用方式。
OpenAPI 始于 Swagger 规范,Swagger 规范已于 2015 年捐赠给 Linux 基金会后改名为 OpenAPI,并定义最新的规范为 OpenAPI 3.0。
OpenAPI 规范(OAS)是一种通用的、和编程语言无关的 API 描述规范,使人类和计算机都可以发现和理解服务的功能,而无需访问源代码、文档或针对接口进行嗅探。正确定义后,使用者可以使用最少的实现逻辑来理解远程服务并与之交互。
springdoc-openapi-ui:https://github.com/springdoc/springdoc-openapi
The springdoc-openapi Java library helps automating the generation of API documentation using Spring Boot projects. springdoc-openapi works by examining an application at runtime to infer API semantics based on Spring configurations, class structure and various annotations.
The library automatically generates documentation in JSON/YAML and HTML formatted pages. The generated documentation can be complemented using swagger-api annotations.
maven地址:https://mvnrepository.com/artifact/org.springdoc/springdoc-openapi-ui
Swagger入门
普通SpringBoot项目中在pom.xml中引入jar包
<dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>2.9.2</version></dependency><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>2.9.2</version></dependency>`在这里插入代码片`
构建SwaggerConfig
packagecom.ca.web.core.config;importjava.util.ArrayList;importjava.util.List;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importcom.ca.common.config.RuoYiConfig;importio.swagger.annotations.ApiOperation;importio.swagger.models.auth.In;importorg.springframework.web.servlet.config.annotation.EnableWebMvc;importspringfox.documentation.builders.ApiInfoBuilder;importspringfox.documentation.builders.PathSelectors;importspringfox.documentation.builders.RequestHandlerSelectors;importspringfox.documentation.service.ApiInfo;importspringfox.documentation.service.ApiKey;importspringfox.documentation.service.AuthorizationScope;importspringfox.documentation.service.Contact;importspringfox.documentation.service.SecurityReference;importspringfox.documentation.service.SecurityScheme;importspringfox.documentation.spi.DocumentationType;importspringfox.documentation.spi.service.contexts.SecurityContext;importspringfox.documentation.spring.web.plugins.Docket;importspringfox.documentation.swagger2.annotations.EnableSwagger2;/**
* Swagger2的接口配置
*
* @author ruoyi
*/@Configuration@EnableWebMvc@EnableSwagger2publicclassSwaggerConfig{/**
* 创建API
*/@BeanpublicDocketcreateRestApi(){returnnewDocket(DocumentationType.SWAGGER_2)// 设置哪些接口暴露给Swagger展示.select()// 扫描所有有注解的api,用这种方式更灵活.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).build();}}
springdoc-openapi-ui入门
(1)springboot工程pom依赖
<!-- 只需要引入这一个依赖就行了 --><dependency><groupId>org.springdoc</groupId><artifactId>springdoc-openapi-ui</artifactId><version>xxx</version></dependency>
(2)SwaggerProperties
@ConfigurationProperties("xxx.swagger")@DatapublicclassSwaggerProperties{/**
* 标题
*/@NotEmpty(message ="标题不能为空")privateString title;/**
* 描述
*/@NotEmpty(message ="描述不能为空")privateString description;/**
* 作者
*/@NotEmpty(message ="作者不能为空")privateString author;/**
* 版本
*/@NotEmpty(message ="版本不能为空")privateString version;/**
* url
*/@NotEmpty(message ="扫描的 package 不能为空")privateString url;/**
* email
*/@NotEmpty(message ="扫描的 email 不能为空")privateString email;/**
* license
*/@NotEmpty(message ="扫描的 license 不能为空")privateString license;/**
* license-url
*/@NotEmpty(message ="扫描的 license-url 不能为空")privateString licenseUrl;}
(3)SwaggerAutoConfiguration
@AutoConfiguration@ConditionalOnClass({OpenAPI.class})@EnableConfigurationProperties(SwaggerProperties.class)@ConditionalOnProperty(prefix ="springdoc.api-docs", name ="enabled", havingValue ="true", matchIfMissing =true)// 设置为 false 时,禁用publicclassSwaggerAutoConfiguration{// ========== 全局 OpenAPI 配置 ==========@BeanpublicOpenAPIcreateApi(SwaggerProperties properties){Map<String,SecurityScheme> securitySchemas =buildSecuritySchemes();OpenAPI openAPI =newOpenAPI()// 接口信息.info(buildInfo(properties))// 接口安全配置.components(newComponents().securitySchemes(securitySchemas)).addSecurityItem(newSecurityRequirement().addList(HttpHeaders.AUTHORIZATION));
securitySchemas.keySet().forEach(key -> openAPI.addSecurityItem(newSecurityRequirement().addList(key)));return openAPI;}/**
* API 摘要信息
*/privateInfobuildInfo(SwaggerProperties properties){returnnewInfo().title(properties.getTitle()).description(properties.getDescription()).version(properties.getVersion()).contact(newContact().name(properties.getAuthor()).url(properties.getUrl()).email(properties.getEmail())).license(newLicense().name(properties.getLicense()).url(properties.getLicenseUrl()));}/**
* 安全模式,这里配置通过请求头 Authorization 传递 token 参数
*/privateMap<String,SecurityScheme>buildSecuritySchemes(){Map<String,SecurityScheme> securitySchemes =newHashMap<>();SecurityScheme securityScheme =newSecurityScheme().type(SecurityScheme.Type.APIKEY)// 类型.name(HttpHeaders.AUTHORIZATION)// 请求头的 name.in(SecurityScheme.In.HEADER);// token 所在位置
securitySchemes.put(HttpHeaders.AUTHORIZATION, securityScheme);return securitySchemes;}/**
* 自定义 OpenAPI 处理器
*/@BeanpublicOpenAPIServiceopenApiBuilder(Optional<OpenAPI> openAPI,SecurityService securityParser,SpringDocConfigProperties springDocConfigProperties,PropertyResolverUtils propertyResolverUtils,Optional<List<OpenApiBuilderCustomizer>> openApiBuilderCustomizers,Optional<List<ServerBaseUrlCustomizer>> serverBaseUrlCustomizers,Optional<JavadocProvider> javadocProvider){returnnewOpenAPIService(openAPI, securityParser, springDocConfigProperties,
propertyResolverUtils, openApiBuilderCustomizers, serverBaseUrlCustomizers, javadocProvider);}// ========== 分组 OpenAPI 配置 ==========/**
* 所有模块的 API 分组
*/@BeanpublicGroupedOpenApiallGroupedOpenApi(){returnbuildGroupedOpenApi("all","");}publicstaticGroupedOpenApibuildGroupedOpenApi(String group){returnbuildGroupedOpenApi(group, group);}publicstaticGroupedOpenApibuildGroupedOpenApi(String group,String path){returnGroupedOpenApi.builder().group(group).pathsToMatch("/admin-api/"+ path +"/**","/app-api/"+ path +"/**").addOperationCustomizer((operation, handlerMethod)-> operation
.addParametersItem(buildTenantHeaderParameter()).addParametersItem(buildSecurityHeaderParameter())).build();}/**
* 构建 Tenant 租户编号请求头参数
*
* @return 多租户参数
*/privatestaticParameterbuildTenantHeaderParameter(){returnnewParameter().name(WebFrameworkUtils.HEADER_TENANT_ID)// header 名.description("租户编号")// 描述.in(String.valueOf(SecurityScheme.In.HEADER))// 请求 header.schema(newIntegerSchema()._default(1L).name(WebFrameworkUtils.HEADER_TENANT_ID).description("租户编号"));// 默认:使用租户编号为 1}/**
* 构建 Authorization 认证请求头参数
*
* 解决 Knife4j <a href="https://gitee.com/xiaoym/knife4j/issues/I69QBU">Authorize 未生效,请求header里未包含参数</a>
*
* @return 认证参数
*/privatestaticParameterbuildSecurityHeaderParameter(){returnnewParameter().name(HttpHeaders.AUTHORIZATION)// header 名.description("认证 Token")// 描述.in(String.valueOf(SecurityScheme.In.HEADER))// 请求 header.schema(newStringSchema()._default("Bearer test1").name(WebFrameworkUtils.HEADER_TENANT_ID).description("认证 Token"));// 默认:使用用户编号为 1}}
(4)yaml文件配置
springdoc:api-docs:enabled:truepath: /v3/api-docs
swagger-ui:enabled:truepath: /swagger-ui
(6)代码开发
packagecom.hello.api.admin;importcom.hello.dto.CommonResult;importcom.hello.dto.User;importio.swagger.v3.oas.annotations.Operation;importio.swagger.v3.oas.annotations.Parameter;importio.swagger.v3.oas.annotations.media.Content;importio.swagger.v3.oas.annotations.media.Schema;importio.swagger.v3.oas.annotations.responses.ApiResponse;importio.swagger.v3.oas.annotations.tags.Tag;@Tag(name ="AdminControllerApi", description ="管理员相关接口")publicinterfaceAdminControllerApi{@Operation(summary ="管理员添加用户",
description ="根据姓名添加用户并返回",
parameters ={@Parameter(name ="name", description ="姓名")},
responses ={@ApiResponse(description ="返回添加的用户", content =@Content(mediaType ="application/json", schema =@Schema(anyOf ={CommonResult.class,User.class}))),@ApiResponse(responseCode ="400", description ="返回400时候错误的原因")})CommonResult<User>addUser(String name);@Operation(summary ="管理员删除用户", description ="根据姓名删除用户")@ApiResponse(description ="返回添加的用户", content =@Content(mediaType ="application/json", schema =@Schema(implementation =User.class)))CommonResult<User>delUser(@Parameter(description ="姓名")String name);@Operation(summary ="管理员更新用户", description ="管理员根据姓名更新用户")@ApiResponse(description ="返回更新的用户", content =@Content(mediaType ="application/json", schema =@Schema(implementation =User.class)))CommonResult<User>updateUser(@Parameter(schema =@Schema(implementation =User.class), required =true, description ="用户类")User user);}
(5)启动访问:127.0.0.1:8080/swagger-ui
版权归原作者 Leo_Hu666 所有, 如有侵权,请联系我们删除。