SpringCloud + React19 集成Scalar的API文档

你好呀,我的老朋友!我是老寇,跟我一起学习集成Scalr API文档

众所周知,Knife4j是一个集Swagger2OpenAPI3 为一体的增强解决方案,但是社区不太活跃,再加上SpringBoot4 发版,迫切需要一个集成 OpenAPI 3.0OpenAPI 3.1 规范的增强解决方案,所以才集成Scalar

React集成Scalar

React集成Scalar文档地址

安装依赖
shell 复制代码
pnpm install @scalar/api-reference-react
配置详情
配置项 类型 是否必填 说明 示例
sources Array OpenAPI 文档源列表,一个配置可以配置多个 API 文档。 [{ title: "认证授权", url: "/api/v3/api-docs" }]
sources.title String API 文档名称,在 Scalar 左侧导航中显示。 "认证授权"
sources.url String OpenAPI(Swagger)JSON 文档地址。 "/api-proxy/auth/api/v3/api-docs"
sources.default Boolean 是否默认选中该文档。 true
proxyUrl String Scalar 的代理地址,用于 Try It、鉴权等请求代理。 "/api-proxy/auth/scalar"
expandAllResponses Boolean 是否默认展开所有 Response。 true
hideClientButton Boolean 是否隐藏 Generate Client(生成客户端)按钮。 true
orderRequiredPropertiesFirst Boolean Model 属性中,是否将必填字段排在前面。 true
expandAllModelSections Boolean 是否默认展开所有 Model 定义。 false
具体代码

apiDoc.tsx

javascript 复制代码
import {ApiReferenceReact} from '@scalar/api-reference-react'
import '@scalar/api-reference-react/style.css'
import { useIntl } from '@@/exports';

export default () => {
    const intl = useIntl();
    const t = (id: string, values?: Record<string, any>) =>
       intl.formatMessage({ id }, values);
    return (
       <ApiReferenceReact
          configuration={
          [
             {
                sources: [
                   {
                      title: '认证授权',
                      url: "/api-proxy/auth/api/v3/api-docs",
                      default: true,
                   }
                ],
                proxyUrl: "/api-proxy/auth/scalar",
                expandAllResponses: true,
                hideClientButton: true,
                orderRequiredPropertiesFirst: true,
                expandAllModelSections: false,
             },
             {
                sources: [
                   {
                      title: '后台管理',
                      url: "/api-proxy/admin/api/v3/api-docs",
                      default: true,
                   }
                ],
                proxyUrl: "/api-proxy/admin/scalar",
                expandAllResponses: true,
                hideClientButton: true,
                orderRequiredPropertiesFirst: true,
                expandAllModelSections: false,
             }
          ]
       }
       />
    );
};

Spring Cloud Gateway集成Scalar

由于代理地址为 /**/scalar 因此,需要在网关层将 /**/scalar 覆盖为 scalar_url

依赖
复制代码
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-gateway-server-webflux</artifactId>
</dependency>
具体代码

ScalarGatewayFilterFactory

java 复制代码
@Slf4j
@Component
public class ScalarGatewayFilterFactory extends AbstractGatewayFilterFactory<ScalarGatewayFilterFactory.@NonNull Config>
       implements Ordered {

    public ScalarGatewayFilterFactory() {
       super(Config.class);
    }

    @Override
    public int getOrder() {
       return Ordered.LOWEST_PRECEDENCE - 2000;
    }

    @NonNull
    @Override
    public GatewayFilter apply(Config config) {
       return (exchange, chain) -> {
          ServerHttpRequest request = exchange.getRequest();
          // 获取uri
          String requestURL = ReactiveRequestUtils.getRequestURL(request);
          // scalar重写地址
          if (ReactiveRequestUtils.pathMatcher("/**/scalar", requestURL)) {
             String scalarUrl = ReactiveRequestUtils.getParamValue(request, "scalar_url");
             URI uri = URI.create(scalarUrl);
             return chain
                .filter(exchange.mutate().request(request.mutate().uri(uri).path(uri.getPath()).build()).build());
          }
          return chain.filter(exchange);
       };
    }

    public static class Config {

    }

}

application.yml

yaml 复制代码
spring:
  cloud:
    gateway:
      server:
        webflux:
          enabled: true
          routes:
            - id: laokou-auth-scalar
              uri: lb://laokou-auth
              predicates:
                - Path=/api-gateway/auth/scalar
              filters:
                - name: Scalar
            - id: laokou-admin-scalar
              uri: lb://laokou-admin
              predicates:
                - Path=/api-gateway/admin/scalar
              filters:
                - name: Scalar

SpringBoot集成Scalar(以laokou-auth为例)

安装依赖
xml 复制代码
<dependency>
  <groupId>org.springdoc</groupId>
  <artifactId>springdoc-openapi-starter-webmvc-scalar</artifactId>
</dependency>
具体代码

OpenApiDocConfig

java 复制代码
@Configuration
public class OpenApiDocConfig {

    @Bean
    OpenAPI openApi() {
       return new OpenAPI()
          .info(new Info().title("API文档")
             .description("API文档")
             .version("1.0.0")
             .contact(new Contact().name("laokou").url("https://github.com/KouShenhai").email("2413176044@qq.com"))
             .license(new License().name("Apache 2.0").url("https://www.apache.org/licenses/LICENSE-2.0.html")))
          .externalDocs(new ExternalDocumentation().description("老寇IoT云平台").url("https://github.com/KouShenhai"))
          .addSecurityItem(new SecurityRequirement().addList(HttpHeaders.AUTHORIZATION))
          .components(new Components().addSecuritySchemes(HttpHeaders.AUTHORIZATION,
                new SecurityScheme().name(HttpHeaders.AUTHORIZATION)
                   .type(SecurityScheme.Type.OAUTH2)
                   .in(SecurityScheme.In.HEADER)
                   .scheme("Bearer")
                   .bearerFormat("JWT")));

    }

}

application.yml

yaml 复制代码
scalar:
  enabled: true
springdoc:
  swagger-ui:
    enabled: false
  api-docs:
    enabled: true
    path: /v3/api-docs
    version: openapi_3_1

我是老寇,我们下次再见啦!

相关推荐
智驭未来掌门人27 分钟前
利用FFmpeg快速实现一个RTSP推流服务器
后端
垚垚学技术_聚焦云原生40 分钟前
K8s Pod 完整生命周期详解
后端
JavaGuide44 分钟前
Github 史诗级故障,与此同时,Cursor 版「GitHub」正式上线!
前端·后端
不一样的少年_1 小时前
修了 Bug、做了重构,为什么老板还是觉得你没产出?
前端·后端·程序员
水深火乐1 小时前
安全地生成验证码、密码和 Token
后端
小强19881 小时前
SQL Server 慢查询怎么定位?一套从“卡”到“快”的完整排查流程
后端
水深火乐1 小时前
interface和any
后端
步行cgn1 小时前
MyBatis Error evaluating expression ‘ids‘. Return value (3) was not iterable 错误详
java·后端
神奇小汤圆1 小时前
Spring Boot + LangChain4j实现RAG——从零搭建企业级知识库问答系统
后端
H_Peak1 小时前
Python运算符与流程控制:if条件判断
后端