拓冰建站拓冰建站
首页 / 资讯中心 / 正文

Scalar Rust 集成:用 scalar_api_reference 在 Axum/Actix-web/Warp 中嵌入 API 文档

Scalar Rust 集成用 scalar_api_reference 在 Axum/Actix-web/Warp 中嵌入 API 文档【免费下载链接】scalarScalar is an open-source API platform: Modern REST API Client Beautiful API References ✨ 1st-Class OpenAPI/Swagger Support项目地址: https://gitcode.com/GitHub_Trending/sc/scalar本文讲解 Scalar 官方 Rust cratescalar_api_reference的完整用法如何把 Scalar API Reference 的 HTML 与静态资源直接嵌入 Rust 二进制通过 JSON 配置注入生成文档页面以及 Axum、Actix-web、Warp 三种框架集成方式。读完本文你可以从零在 Rust Web 服务中挂载一个可交互的 OpenAPI 文档页面理解其模板渲染、资产内嵌rust-embed与 MIME 处理的源码级实现并掌握 Agent AI 聊天助手的配置方式。它解决什么问题Scalar 提供官方的 Rust crate用于在 Rust Web 应用中渲染 Scalar API 文档。其核心特性包括将 Scalar 的 HTML/JS 资产直接嵌入 Rust 二进制无需在部署环境中分发前端文件框架无关的核心 API并为流行 Web 框架提供可选集成feature 门控通过 JSON 注入简单配置自动按正确的 MIME 类型提供静态资产。从源码结构看这一嵌入二进制能力由 src/lib.rs 中的RustEmbed派生实现/// Embedded UI assets #[derive(RustEmbed)] #[folder ui/)] struct Assets; /// Get a static asset by path pub fn get_asset(path: str) - OptionVecu8 { Assets::get(path).map(|d| d.data.into()) }编译时 ui/index.html 等文件被打包进二进制运行时无需文件系统即可读取。安装在Cargo.toml中添加依赖[dependencies] scalar_api_reference 0.1.0 serde_json 1.0若需要框架集成通过 Cargo feature 开启。Cargo.toml 中定义了可选依赖及其版本Feature引入的依赖版本axumaxum、axum-extra、tokioaxum 0.8.8、axum-extra 0.12.5、tokio 1.51.1actix-webactix-web4.13.0warpwarp、tokiowarp 0.4.2核心依赖为rust-embed8.11.0、serde、serde_json这些始终启用与框架无关。仓库提供了三个可运行示例[[example]]目标声明了各自的required-featuresexamples/axum.rs、examples/actix.rs、examples/warp.rs。核心用法生成 HTML不带任何 feature 时crate 暴露框架无关的核心函数scalar_html、scalar_html_default、scalar_html_from_json以及对应的_default变体、get_asset、get_asset_with_mime。use scalar_api_reference::{scalar_html, scalar_html_default, get_asset, get_asset_with_mime}; use serde_json::json; // 使用 CDN 生成带配置的 HTML let configuration json!({ url: /openapi.json, theme: purple }); // 使用 CDN 回退 let html1 scalar_html(configuration, None); // 或使用便捷函数 let html2 scalar_html_default(configuration); // 使用自定义 JS bundle URL let html3 scalar_html(configuration, Some(/custom-scalar.js)); // 获取静态资产 if let Some(js_content) get_asset(scalar.js) { // 返回 JavaScript 文件内容 } // 获取带 MIME 类型的静态资产 if let Some((mime_type, content)) get_asset_with_mime(scalar.js) { // 以正确的 MIME 类型返回文件 }参数含义scalar_html(config, js_bundle_url)的第一个参数是serde_json::Value形式的配置对象第二个参数是Optionstr——为None时回退到 CDN为Some(url)时使用你提供的 JS bundle 地址。模板渲染的底层机制render_scalar 揭示了生成过程的本质——占位符替换pub fn render_scalar(config_json: str, js_bundle_url: Optionstr) - String { let html_template include_str!(../ui/index.html); let js_url js_bundle_url.unwrap_or(https://cdn.jsdelivr.net/npm/scalar/api-reference); html_template .replace(__CONFIGURATION__, config_json) .replace(__JS_BUNDLE_URL__, js_url) }即把 ui/index.html 模板中的__CONFIGURATION__和__JS_BUNDLE_URL__两个占位符替换掉。模板本体非常精简body div idapp/div !-- Load the Script -- script src__JS_BUNDLE_URL__/script !-- Initialize the Scalar API Reference -- script Scalar.createApiReference(#app, __CONFIGURATION__) /script /body因此最终页面只有一个挂载点#app配置以字面量内联进script前端 bundle 加载后调用Scalar.createApiReference(#app, 配置)完成渲染。若你持有 JSON 字符串例如来自配置中心或文件可以使用scalar_html_from_json(config_json, js_bundle_url)它在解析失败时返回Result_, serde_json::Error而非 panic——源码测试 验证了非法 JSON 返回Err、空对象{}也能正常生成使用 CDN 的 HTML。JS Bundle URLCDN 与自定义库支持两种方式加载 Scalar JavaScript bundleCDN默认js_bundle_url传None时模板中的script src指向https://cdn.jsdelivr.net/npm/scalar/api-reference。自定义 bundle URL传入自有路径例如把 bundle 静态托管到自己的服务或在无外网环境内嵌分发// 使用你的自定义 URL let html scalar_html(configuration, Some(/path/to/scalar.js));测试用例lib.rs 的test_scalar_html_generation确认了两种模式下生成的 HTML 分别包含自定义路径或 CDN 地址且配置中的url、theme均完整保留在输出中。静态资产服务如果需要自行提供额外静态资产CSS、JS、图片使用资产函数use scalar_api_reference::get_asset_with_mime; // 在你的路由处理器中 if let Some((mime_type, content)) get_asset_with_mime(scalar.js) { // 返回带正确 MIME 类型与内容的响应 }MIME 类型由文件扩展名决定映射表见 get_mime_typehtml → text/html、js → application/javascript、css → text/css、json → application/json、png → image/png、svg → image/svgxml、ico → image/x-icon未知扩展名回退为application/octet-stream。该映射有专门的测试 test_mime_type_detection 逐条覆盖test_get_asset_with_mime则验证index.html返回text/html、scalar.js返回application/javascript。资产不存在时如get_asset(non-existent.txt)返回None由调用方决定如何处理各框架封装默认返回 404。框架集成三个框架模块都由 feature 门控模块内提供两层 API响应构造器低层返回 HTML 响应体 路由生成器高层同时挂载文档页与scalar.js资产路由。Axum开启axumfeature 后使用scalar_api_reference::axum模块实现见 lib.rsscalar_response(config, js_bundle_url) - HtmlString直接构造 HTML 响应scalar_response_from_json(...) - ResultHtmlString, serde_json::Errorrouter(path, config) - Router一次生成文档路由与{path}/scalar.js资产路由文档页的 bundle URL 自动指向本地资产路由实现完全离线可用routes(path, config) - (Router, Router)拆分为文档路由与资产路由两个 Router便于自行组合。仓库自带的完整示例examples/axum.rsuse axum::Router; use scalar_api_reference::axum::router; use serde_json::json; #[tokio::main] async fn main() { let config json!({ url: https://registry.scalar.com/scalar/apis/galaxy?formatjson, theme: purple, }); let app Router::new().merge(router(/scalar, config)); let listener tokio::net::TcpListener::bind(0.0.0.0:3000).await.unwrap(); println!(Server running on http://localhost:3000/scalar); axum::serve(listener, app).await.unwrap(); }Actix-web开启actix-webfeature 后使用scalar_api_reference::actix_web模块scalar_response/scalar_response_from_json构造HttpResponseconfig(path, config)返回一个impl Fn(mut ServiceConfig)闭包用于App::configure。示例examples/actix.rsuse actix_web::{App, HttpServer}; use scalar_api_reference::actix_web::config; use serde_json::json; #[actix_web::main] async fn main() - std::io::Result() { let config_json json!({ url: https://registry.scalar.com/scalar/apis/galaxy?formatjson, theme: kepler, }); println!(Server running on http://localhost:8080/scalar); HttpServer::new(move || App::new().configure(config(/scalar, config_json))) .bind(127.0.0.1:8080)? .run() .await }Warp开启warpfeature 后使用scalar_api_reference::warp模块scalar_reply/scalar_reply_from_json返回impl warp::Replyroutes(path, config)与separate_routes(path, config)分别返回组合 Filter 或拆分的两个 Filter。Warp 有一个与其他框架不同的注意点path 不应包含前导斜杠用scalar而非/scalar。源码中 warp 模块 对此做了防御性处理trim_start_matches(/)并且刻意让更具体的资产路由scalar/scalar.js优先于文档路由匹配文档路由再用warp::path::end()限制为精确匹配。示例examples/warp.rsuse scalar_api_reference::warp::routes; use serde_json::json; #[tokio::main] async fn main() { let config json!({ url: https://registry.scalar.com/scalar/apis/galaxy?formatjson, theme: kepler, layout: classic }); let scalar routes(scalar, config); println!(Server running on http://localhost:3030/scalar); warp::serve(scalar).run(([127, 0, 0, 1], 3030)).await; }社区集成除官方支持的三个框架外文档还列出了几个社区集成方案以名称指代可另行检索utoipa-scalarutoipa 生态中的 Scalar 集成、Aide一个 OpenAPI 辅助库、以及框架无关的scalar-doccrate。配置项配置对象支持所有标准 Scalar 选项常用项包括url你的 OpenAPI 文档路径layout布局风格classic或moderntheme主题名如purple、blue、greendarkMode启用深色模式。完整配置参考见 configuration 文档。配置 Agent AI 聊天助手Agent 为 API Reference 添加 AI 聊天界面。在 localhost 下默认启用且带有限免费额度10 条消息生产环境需要 Agent key获取方式见 Agent key 指南。设置 Agent API key顶层let configuration json!({ url: /openapi.json, agent: { key: your-agent-scalar-key } });禁用 Agentlet configuration json!({ url: /openapi.json, agent: { disabled: true } });多文档场景下按 source 配置 keylet configuration json!({ sources: [ { url: https://api.example.com/openapi/v1.json, agent: { key: your-key-for-api-v1 } }, { url: https://api.example.com/openapi/v2.json } ] });除了直接手写 JSONcrate 还提供类型安全的构建器config.rs 中定义了AgentOptions与Source两个结构体均带#[serde(rename_all camelCase)]与skip_serializing_if Option::is_none属性——即空字段不会出现在序列化结果中最终 JSON 键名是key/disabled与url/agent。构建器 APIAgentOptions::with_key(key)设置生产环境 keyAgentOptions::disabled()禁用当前作用域全局或单个 source的 AgentSource::new(url)与.with_agent(...)为多文档配置中的每个文档单独挂 Agent 选项。用法示例use scalar_api_reference::{scalar_html_default, AgentOptions, Source}; use serde_json::json; // 顶层 agent key let agent AgentOptions::with_key(your-agent-scalar-key); let config json!({ url: /openapi.json, agent: serde_json::to_value(agent).unwrap() }); let html scalar_html_default(config); // 或禁用 agent let config json!({ url: /openapi.json, agent: serde_json::to_value(AgentOptions::disabled()).unwrap() }); // 按 source 配置 agent多文档 let sources vec![ Source::new(https://api.example.com/v1.json).with_agent(AgentOptions::with_key(key-for-v1)), Source::new(https://api.example.com/v2.json), ]; let config json!({ sources: serde_json::to_value(sources).unwrap() });更完整的 Agent 说明见 configuration 文档的 Agent 章节与 如何获取 Agent key。测试如何验证这些行为crate 的单元测试覆盖了上述全部承诺可作为行为契约参考src/lib.rs 测试模块test_scalar_html_generation/test_scalar_html_from_json自定义 bundle 与 CDN 两种模式下HTML 包含配置内容、正确 bundle 地址且结构完整test_get_asset/test_get_asset_with_mimeindex.html、scalar.js可取到不存在的路径返回NoneMIME 分别为text/html与application/javascripttest_agent_options_in_config/test_sources_with_agent_in_configAgentOptions::with_key、AgentOptions::disabled与带 agent 的Source序列化后均正确进入生成的 HTMLtest_edge_cases空配置仍可渲染URL 含查询参数与特殊字符时配置原样保留。各框架模块另有独立的 feature 门控测试axum_tests、actix_tests、warp_tests验证响应构造、JSON 解析错误传播与路由创建不 panic。小结与延伸阅读scalar_api_reference的设计把生成 HTML与服务路由解耦核心函数与资产函数始终可用框架路由是可选的语法糖。资产通过 rust-embed 编入二进制MIME 映射、模板占位符替换与路由拆分逻辑均有源码与测试可查证。官方 crate 源码integrations/rust框架集成文档Axum、Actix-web、Warp主题文档documentation/themes.md完整配置参考documentation/configuration.mdAgent key 获取documentation/guides/agent/key.md【免费下载链接】scalarScalar is an open-source API platform: Modern REST API Client Beautiful API References ✨ 1st-Class OpenAPI/Swagger Support项目地址: https://gitcode.com/GitHub_Trending/sc/scalar创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
分享:

看完干货,该让你的企业上线了

免费需求沟通 · 48 小时内出具建站方案 · 河南本地可上门