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

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

相关推荐
麻瓜code22 分钟前
【Agent】Spring AI RAG 实战:本地向量库 + 云端知识库
java·人工智能·spring
BS30813_vx27 分钟前
基于 Express + uni-app 的养老院管理系统设计与实现
后端·uni-app·express
明月_清风38 分钟前
DeepSeek Harness 安全审计实录:四个 PoC 揭露的 Agent 运行时"信任危机"
后端·安全·agent
苏三说技术1 小时前
再见了EasyExcel,我决定用Apache Fesod
后端
XR1234567881 小时前
医院移动医护零漫游无线网络选型指南
java·后端·struts
水巷石子1 小时前
学习langChain4j的第二天,体验springBoot中的starter
java·spring boot·学习·spring·langchain4j
ly76891 小时前
Spring Bean生命周期全流程:从BeanDefinition到销毁
java·后端·spring·bean生命周期·beandefinition·初始化回调
leeyi2 小时前
在 Go 里跑不信任的代码:WASM 沙箱的四道墙(第107篇)
后端
摇滚侠2 小时前
《Spring Boot 3:高级与架构设计》第 1 章 BeanDefinitionRegistry 阅读笔记 3
spring boot·笔记·后端
烂蜻蜓2 小时前
Flask入门教程(三十一):实用函数与类API——全局工具函数速查
后端·python·flask