尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

Scalar FastAPI 集成实战:scalar-fastapi 插件完整配置参考与源码实现原理

Scalar FastAPI 集成实战:scalar-fastapi 插件完整配置参考与源码实现原理 Scalar FastAPI 集成实战scalar-fastapi 插件完整配置参考与源码实现原理【免费下载链接】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 官方的 FastAPI 集成文档为主线讲解如何用scalar-fastapi包在 FastAPI 应用中一行代码挂载交互式 OpenAPI 文档Scalar API Reference覆盖add_scalar_reference快速接入、自定义路由、多 OpenAPI 源sources、直接传入 OpenAPI 内容、Agent AI 聊天等用法并完整整理全部配置参数的默认值与取值随后结合仓库内 插件源码 与 测试用例剖析配置项如何被序列化进Scalar.createApiReference、枚举与纯字符串为何可以互换、以及标题转义与/script逃逸防护的实现细节。读完你可以直接在 FastAPI 项目中落地一套可定制、可多源、可关闭遥测与 Agent 的 API 文档方案。一、安装Scalar 的 FastAPI 插件以 PyPI 包scalar-fastapi发布MIT 许可要求 Python ≥ 3.9依赖fastapi、pydantic2、typing_extensions4.8详见 pyproject.tomlpip install scalar-fastapi仓库中 playground 环境清单 锁定了一套经过验证的版本组合例如fastapi0.135.3、pydantic2.13.0、scalar-fastapi1.8.2、uvicorn0.44.0可以作为本地验证的参考基线。二、快速开始一行代码挂载 /scalarFastAPI 自带 OpenAPI 支持默认输出到/openapi.jsonScalar 正是利用这一点把文档页面“零成本”挂进来。最快的方式是一行调用——add_scalar_reference会替你注册路由并自动从应用实例读取标题和 OpenAPI URLfrom fastapi import FastAPI from scalar_fastapi import add_scalar_reference app FastAPI() add_scalar_reference(app)随后在浏览器打开/scalar即可看到文档页。你可以更换路由并把get_scalar_api_reference接受的任意参数透传进去from scalar_fastapi import add_scalar_reference, Theme add_scalar_reference(app, route/docs/scalar, themeTheme.KEPLER)add_scalar_reference自身只接受route默认/scalar和include_in_schema默认False两个专属参数其余关键字参数全部转发给get_scalar_api_reference。源码视角add_scalar_reference 到底做了什么实现代码 只有短短十几行值得完整理解def add_scalar_reference( app: FastAPI, *, route: str /scalar, include_in_schema: bool False, **kwargs: Any, ) - FastAPI: # Fall back to the apps own values, but let callers override either one. kwargs.setdefault(openapi_url, app.openapi_url) kwargs.setdefault(title, app.title) app.get(route, include_in_schemainclude_in_schema) async def scalar_html() - HTMLResponse: return get_scalar_api_reference(**kwargs) return app从源码结构看有四个关键设计点自动填充通过kwargs.setdefault从app.openapi_urlFastAPI 默认即/openapi.json和app.title兜底取值调用方显式传入的title、openapi_url优先于应用默认值。不污染 OpenAPI 文档include_in_schema默认为False/scalar路由不会出现在/openapi.json的paths里。这一点由 测试test_route_is_hidden_from_schema_by_default验证。可链式调用函数返回app本身测试test_returns_the_app_for_chaining断言add_scalar_reference(app) is app。自定义路由即唯一路由传route/docs/scalar时默认/scalar不再注册测试test_custom_route_and_passthrough_kwargs断言此时访问/scalar返回 404且透传的themeTheme.KEPLER、titleDocs均生效。仓库 playground 就是官方示例add_scalar_reference(app, themeTheme.KEPLER)加上两个业务路由按 playground 说明 执行pip install -r requirements.txt后运行uvicorn main:app --reload访问http://127.0.0.1:8000/scalar即可体验。三、自定义路由完全掌控 get_scalar_api_reference如果你需要完全控制路由行为例如挂到自定义前缀、加权限依赖直接用get_scalar_api_reference自己声明路由from fastapi import FastAPI from scalar_fastapi import get_scalar_api_reference app FastAPI() app.get(/scalar, include_in_schemaFalse) async def scalar_html(): return get_scalar_api_reference( # Your OpenAPI document openapi_urlapp.openapi_url, # Avoid CORS issues (optional) scalar_proxy_urlhttps://proxy.scalar.com, )get_scalar_api_reference返回的是一个HTMLResponse其 HTML 骨架为head中放title、favicon、默认主题 CSS仅默认主题时注入body中一个div idapp挂载点然后加载scalar_js_url指向的脚本并执行Scalar.createApiReference(#app, {config_json})。这个“服务端生成静态 HTML 浏览器端拉取 JS 渲染”的模式意味着插件本身不打包任何前端资源文档页面的实际渲染由 CDN 上的scalar/api-reference完成。四、多 OpenAPI 源sources一个 Scalar 实例可以同时展示多份 OpenAPI 文档每个源通过OpenAPISourcePydantic 模型extraforbid严格拒绝未知字段配置from scalar_fastapi import get_scalar_api_reference, OpenAPISource app.get(/scalar, include_in_schemaFalse) async def scalar_html(): return get_scalar_api_reference( sources[ OpenAPISource( titleUser API, url/openapi.json, defaultTrue ), OpenAPISource( titleAdmin API, url/admin/openapi.json ), OpenAPISource( titleExternal API, content{openapi: 3.0.0, ...} ) ], titleMy API Documentation )源码中sources会被model_dump(exclude_noneTrue)转为字典列表后写入配置的sources键见 配置构建逻辑None字段自动剔除。直接传入 OpenAPI 内容content除了url指向文档地址也可以把 OpenAPI 文档直接作为字符串JSON 或 YAML或字典传入app.get(/scalar, include_in_schemaFalse) async def scalar_html(): return get_scalar_api_reference( content{openapi: 3.0.0, info: {title: My API}}, titleMy API )三者存在明确的优先级sourcescontentopenapi_url若三者均未提供则回退到标准 FastAPI 地址/openapi.json见 优先级分支。五、Agent在 API 文档中内置 AI 聊天Agent 为 API 文档添加 AI 聊天界面。默认在 localhost 上可用免费消息有限生产环境需要使用 Agent key获取方式见 Agent key 指南完整说明见 Agent 配置章节。按源启用 Agent带 keyfrom scalar_fastapi import get_scalar_api_reference, OpenAPISource, AgentScalarConfig app.get(/scalar, include_in_schemaFalse) async def scalar_html(): return get_scalar_api_reference( sources[ OpenAPISource( titleUser API, url/openapi.json, defaultTrue, agentAgentScalarConfig(keyyour-agent-scalar-key), ), ], titleMy API Documentation )整体禁用 Agentfrom scalar_fastapi import get_scalar_api_reference, AgentScalarConfig app.get(/scalar, include_in_schemaFalse) async def scalar_html(): return get_scalar_api_reference( openapi_url/openapi.json, agentAgentScalarConfig(disabledTrue), )AgentScalarConfig是严格模式 Pydantic 模型只有两个字段key生产环境必填localhost 之外使用 Agent 需要 key与disabled置True表示完全关闭多余字段会直接报错。两个方向的序列化均被测试覆盖顶层agent输出agent: {disabled: true}按源agent输出在sources内部见 相关测试。六、完整配置参数参考get_scalar_api_reference支持的全部参数如下默认值与 函数签名 一致当前可用的更多配置语义见 官方配置总览。核心配置参数默认值说明openapi_urlNoneScalar 要加载的 OpenAPI URL。若提供了content或sources此参数被忽略contentNone直接传入 OpenAPI/Swagger 文档字符串JSON 或 YAML或字典。若提供了sources此参数被忽略sourcesNone多份 OpenAPI 文档列表每个源可含title、slug、url、content、default等字段titleScalar页面title浏览器标签页标题scalar_js_urlhttps://cdn.jsdelivr.net/npm/scalar/api-reference加载 Scalar JavaScript 的地址通常指向 CDN可换成自建/私有源scalar_favicon_urlhttps://fastapi.tiangolo.com/img/favicon.png页面 favicon 地址此默认值见 源码签名OpenAPISource 字段使用多源时每个OpenAPISource可配置title默认None- API 的显示名称。未提供时回退为API #1、API #2等slug默认None- API 的 URL 标识。未提供时由 title 或索引自动生成url默认None- OpenAPI 文档地址JSON 或 YAML与content互斥content默认None- 直接文档内容JSON/YAML 字符串或字典与url互斥default默认False- 多源时该源是否为默认源agent默认None- 该源的 Agent 配置key、disabled详见 Agent 配置。显示选项layout默认Layout.MODERNshow_sidebar默认Truehide_models默认Falsehide_search默认False- 是否显示侧边栏搜索框hide_test_request_button默认False- 是否显示 “Test Request” 按钮hide_download_button默认False-已弃用请改用document_download_type源码中它仍被支持但仅在为True时写入hideDownloadButtondocument_download_type默认DocumentDownloadType.BOTH- 文档下载按钮提供的文件类型选项JSON、YAML、BOTH、NONEshow_developer_tools默认localhost- 顶部开发者工具面板何时显示选项always、localhost、neverplugin_urls默认None/空- 提供附加 API Reference 插件的 ESM 模块 URL 列表每个模块在 API Reference 挂载前被浏览器导入该参数见 源码 DocDocumentDownloadType 枚举from scalar_fastapi import DocumentDownloadType # 可用选项 DocumentDownloadType.JSON # 仅下载 JSON DocumentDownloadType.YAML # 仅下载 YAML DocumentDownloadType.BOTH # JSON 和 YAML 都提供默认 DocumentDownloadType.NONE # 隐藏下载按钮主题与外观dark_mode默认None- 初始是否开启暗色模式留空则跟随读者偏好force_dark_mode_state默认None- 强制暗色模式始终处于该状态取值dark或lighthide_dark_mode_toggle默认False- 是否隐藏暗色模式切换按钮with_default_fonts默认True- 是否使用默认字体Inter 与 JetBrains Monocustom_css默认- 应用到 API 文档页的自定义 CSS 字符串theme默认Theme.DEFAULT- 主题选择见下文 Theme 枚举搜索与导航search_hot_key默认SearchHotKey.Kdefault_open_all_tags默认Falseexpand_all_model_sections默认False- 是否默认展开所有模型章节expand_all_responses默认False- 是否默认展开所有响应章节order_required_properties_first默认True- schema 对象中是否将必填属性排在前面order_schema_properties_by默认alpha- schema 属性排序选项alpha字母序、preserve保持原文档顺序服务器配置base_server_url默认- 给所有相对 server 地址加前缀的基础 URLservers默认None/空- OpenAPI Server Object 列表每项必须含urlstring可选descriptionstring与variablesmap。示例[{url: https://api.example.com, description: Production}]hidden_clients默认无- 隐藏指定客户端。接受字符串列表或“目标名 → 布尔值/客户端名列表”的字典布尔值表示隐藏该目标下全部客户端兼容旧版列表写法认证authentication默认None/空- 附加认证信息字典按认证 scheme 名映射到凭证结构hide_client_button默认False- 是否隐藏侧边栏与弹窗中的客户端按钮persist_auth默认False- 是否把认证凭证持久化到 local storage高级选项scalar_js_url默认https://cdn.jsdelivr.net/npm/scalar/api-referencescalar_proxy_url默认- 代理地址用于规避跨域问题integration默认fastapi- 集成标记写入配置的_integration键设为None则完全省略theme默认Theme.DEFAULTagent默认None- 设为AgentScalarConfig(disabledTrue)可整体关闭 Agent按源配 key 请使用OpenAPISource的agent字段。详见 Agentoverrides默认None/空- 直接合并进最终config字典的覆盖项该字典即Scalar.createApiReference(#app, ...)的第二个参数telemetry默认True- 开关 API 客户端使用遥测仅记录是否有请求经 API client 发出Layout 枚举from scalar_fastapi import Layout # 可用选项 Layout.MODERN # 现代布局默认 Layout.CLASSIC # 经典布局SearchHotKey 枚举SearchHotKey每个字母对应一个成员SearchHotKey.A至SearchHotKey.Z。所选键会与平台修饰键组合使用macOS 为 Cmd其他平台为 Ctrl。默认是SearchHotKey.K。from scalar_fastapi import SearchHotKey get_scalar_api_reference( openapi_url/openapi.json, search_hot_keySearchHotKey.S, # Cmd/Ctrl S )Theme 枚举from scalar_fastapi import Theme # 可用选项默认 Theme.DEFAULT Theme.DEFAULT Theme.ALTERNATE Theme.MOON Theme.PURPLE Theme.SOLARIZED Theme.BLUE_PLANET Theme.SATURN Theme.KEPLER Theme.MARS Theme.DEEP_SPACE Theme.LASERWAVE Theme.NONE # 不使用任何 Scalar 主题渲染主题枚举共 12 个成员且取值互不相同bluePlanet、deepSpace等为驼峰字符串这一点由 测试 逐一断言。七、源码实现原理配置如何变成页面只序列化“非默认值”配置构建段 的策略是从空config字典开始逐项判断——只有当参数偏离默认值时才写入对应的驼峰键如proxyUrl、layout、showSidebar、searchHotKey等最后把overrides整体config.update(overrides)。好处是生成的内联 JSON 尽量精简test_default_parameters测试专门验证了默认配置下proxyUrl、layout、theme、agent等键均不出现在Scalar.createApiReference的配置段中。枚举与纯字符串等价函数入口先做统一归一化layout layout.value if isinstance(layout, Enum) else layout theme theme.value if isinstance(theme, Enum) else theme search_hot_key search_hot_key.value if isinstance(search_hot_key, Enum) else search_hot_key document_download_type ( document_download_type.value if isinstance(document_download_type, Enum) else document_download_type )因此thememoon与themeTheme.MOON生成的 HTML 完全一致——test_string_and_enum_produce_identical_output直接对两种调用产出的 HTML 做了逐字节相等断言而默认值字符串modern、default、k同样会被省略。默认主题的 CSS 注入当且仅当theme default时模板会把一段内置的scalar_themeCSS定义.light-mode/.dark-mode下--scalar-color-*、--scalar-background-*、--scalar-sidebar-*等约 200 行 CSS 变量注入style标签选择其他主题或Theme.NONE时这段内联样式不出现页面改由 CDN 脚本按theme键处理。test_default_theme_string_still_injects_styles用 CSS 变量--scalar-color-accent是否存在来验证这一行为。安全细节标题转义与脚本逃逸防护生成 HTML 前有专门的两层防护见 源码注释与实现page_title escape_html(title) if title else Scalar config_json json.dumps(config).replace(/, \\/)title经过html.escape含script的标题会被转义为lt;scriptgt;不会注入标记序列化后的配置 JSON 中所有/替换为\/防止content里夹带的/script提前终止内联script块。对应测试test_special_characters_in_title_are_escaped与test_content_with_closing_script_tag_cannot_break_out分别用scriptalert(xss)/script标题和/scriptscriptalert(1)/script文档内容验证了这两道防线JSON 中\/是合法转义浏览器解析后仍还原为/不影响 OpenAPI 内容本身。测试与运行验证单元测试 覆盖了HTML 结构!doctype html、div idapp、Scalar.createApiReference(#app、全部主题的序列化、servers/authentication/hidden_clients复杂结构、integrationNone时_integration不出现、show_developer_toolsnever、FastAPITestClient端到端请求/scalar返回text/html等另有 集成测试 与 导入测试 保证__all__导出面add_scalar_reference、get_scalar_api_reference、Layout、OpenAPISource、AgentScalarConfig、SearchHotKey、Theme、DocumentDownloadType见 包导出稳定版本同步机制pyproject.toml中 Hatchling 的[tool.hatch.version]直接从 package.json 的version字段取版本号保证 Python 包与 monorepo 版本一致。八、小结scalar-fastapi的设计非常克制服务端只负责“按 Pythonic 参数生成一段携带精简配置的静态 HTML”真正的工作交给 CDN 上的scalar/api-reference前端。对使用者的核心心智模型是三件事——接入口add_scalar_reference(app)一行接入或get_scalar_api_reference自定义路由数据源优先级sourcescontentopenapi_url 兜底/openapi.json一切参数皆默认值省略只写偏离默认值的配置项另可用overrides做最终兜底覆盖agent、telemetry、show_developer_tools提供了行为开关scalar_js_url、scalar_proxy_url支持私有化部署与代理。结合上文配置表与源码路径你可以在 FastAPI 项目中完整落地并验证这套方案所有关键行为都能在 integrations/fastapi 目录下找到对应的实现与测试依据。【免费下载链接】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),仅供参考
返回列表