SpringCloud + React19 集成Scalar的API文档

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

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

React集成Scalar

React集成Scalar文档地址

安装依赖

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

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

@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

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为例)

安装依赖

<dependency>
  <groupId>org.springdoc</groupId>
  <artifactId>springdoc-openapi-starter-webmvc-scalar</artifactId>
</dependency>

具体代码

OpenApiDocConfig

@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

scalar:
  enabled: true
springdoc:
  swagger-ui:
    enabled: false
  api-docs:
    enabled: true
    path: /v3/api-docs
    version: openapi_3_1

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

posted @ 2026-07-07 06:24  k↑  阅读(1)  评论(0)    收藏  举报