ARTICLE DETAIL

资讯详情

深耕网站视觉设计与运营推广的一线实战洞察。

Scalar FastAPI 集成快速上手:从 Playground 到生产级 API 参考文档

Scalar FastAPI 集成快速上手:从 Playground 到生产级 API 参考文档 Scalar FastAPI 集成快速上手从 Playground 到生产级 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本指南以integrations/fastapi集成中的 Playground 示例为主线带你从零搭建一套基于 FastAPI Scalar 的交互式 API 文档安装依赖、启动服务、访问/scalar端点并深入scalar_fastapi插件源码理解add_scalar_reference一行挂载背后的工作原理与全部配置参数。读完你将掌握如何在任意 FastAPI 项目中一键渲染美观、可调试的 OpenAPI/Swagger 参考文档并学会通过主题、布局、多数据源等参数定制文档界面。环境准备安装依赖Scalar FastAPI 插件是托管在 PyPI 上的scalar-fastapi包Playground 示例的所有依赖已固化在integrations/fastapi/playground/requirements.txt中。进入示例目录后执行pip install -r requirements.txt如果你的机器上同时存在 Python 2/3 多套环境部分系统需要使用pip3代替pip这取决于你本机的 Python 安装方式例如pip3 install -r requirements.txt查看 playground/requirements.txt 可以看到依赖被精确锁定fastapi0.135.3、pydantic2.13.0、uvicorn0.44.0以及本插件的核心依赖scalar-fastapi1.8.2。其中PyYAML用于解析 OpenAPI 文档中的 YAML 内容watchfiles配合 Uvicorn 的--reload实现热重载。启动应用依赖安装完成后在integrations/fastapi/playground目录下运行uvicorn main:app --reloadmain指入口模块main.pyapp指其中创建的FastAPI()实例--reload开启开发模式热重载修改main.py后服务自动重启无需手动操作。启动成功后控制台会输出Uvicorn running on http://127.0.0.1:8000。此时访问http://127.0.0.1:8000/scalar即可看到由 Scalar 渲染的交互式 API 参考文档界面。理解 Playground 的核心代码Playground 的完整源码位于 integrations/fastapi/playground/main.py核心逻辑非常精简from typing import Union from fastapi import FastAPI import sys import os # Use the local scalar_fastapi package sys.path.insert(0, os.path.join(os.path.dirname(__file__), ..)) from scalar_fastapi import add_scalar_reference, Theme app FastAPI() # One line to serve the API reference at /scalar. Any get_scalar_api_reference # option can be passed through, like the theme below. add_scalar_reference(app, themeTheme.KEPLER) app.get(/) def read_root(): return {Hello: World} app.get(/items/{item_id}) def read_item(item_id: int, q: Union[str, None] None): return {item_id: item_id, q: q}要点说明本地包引入技巧sys.path.insert(0, ...)把上一级目录加入模块搜索路径使示例直接使用仓库内的scalar_fastapi源码而非 PyPI 安装版本方便开发调试一行挂载add_scalar_reference(app, themeTheme.KEPLER)即在/scalar路由上挂载 Scalar 文档界面并指定了 KEPLER 主题路由不会污染 OpenAPI Schemaadd_scalar_reference注册的路由默认include_in_schemaFalse/scalar不会出现在你的/openapi.json中这一点有测试专门验证见下文。深入源码add_scalar_reference 的实现原理核心实现位于 integrations/fastapi/scalar_fastapi/scalar_fastapi.py插件对外暴露两个关键 APIget_scalar_api_reference(**kwargs) - HTMLResponse根据配置生成一段完整的 HTML 页面add_scalar_reference(app, route/scalar, include_in_schemaFalse, **kwargs)在 FastAPI 应用上注册路由并透传所有配置。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可见它做了三件事自动从app.openapi_url和app.title取值作为默认数据源与页面标题调用者可覆盖注册一个返回 HTML 的 GET 路由把app原样返回以支持链式调用。这就是为什么你能用add_scalar_reference(app, themeTheme.KEPLER)一行完成全部挂载。HTML 页面生成链路get_scalar_api_reference内部先把所有参数整理为一个 JSON 配置对象再拼接出包含div idapp/div占位符、CDN 脚本标签和初始化代码的 HTML!-- Load the Script -- script srchttps://cdn.jsdelivr.net/npm/scalar/api-reference/script !-- Initialize the Scalar API Reference -- script Scalar.createApiReference(#app, { ...config... }) /script从源码可以观察到两个值得注意的安全细节标题转义page_title escape_html(title) if title else Scalar防止标题注入恶意 HTML配置 JSON 防逃逸config_json json.dumps(config).replace(/, \\/)防止 OpenAPI 文档内容中的/script破坏内联脚本块。对应的测试见 test_scalar_fastapi.py 中的test_special_characters_in_title_are_escaped与test_content_with_closing_script_tag_cannot_break_out。核心配置参数全解析get_scalar_api_reference支持 40 个关键字参数源码中每个参数都带有Doc注释。下面按用途分组梳理最常用的一批默认值以源码为准。数据源三选一的优先级规则参数类型默认值说明openapi_urlstr \| None自动取app.openapi_urlScalar 加载的 OpenAPI URL通常是/openapi.jsoncontentstr \| dict \| NoneNone直接传入 OpenAPI 文档JSON/YAML 字符串或字典优先级高于openapi_urlsourceslist[OpenAPISource] \| NoneNone多文档渲染优先级最高源码中的判断顺序为sources优先 →content其次 →openapi_url→ 兜底/openapi.json。若三者都未指定Scalar 会加载 FastAPI 标准的/openapi.json。多数据源OpenAPISourceOpenAPISource是 Pydantic 模型extraforbid支持字段titleAPI 显示名缺省时按 API #1、API #2 自动编号slugURL 标识符缺省时由 title 或序号自动生成url/contentOpenAPI 文档地址或内联内容二者互斥default是否作为默认展示的源agent为该源单独配置 Agent Scalarkey或disabled。示例from scalar_fastapi import OpenAPISource add_scalar_reference( app, sources[ OpenAPISource(titleUser Service, url/openapi.json, defaultTrue), OpenAPISource(titlePayment Service, url/payments/openapi.json), ], )外观主题与布局Theme枚举共 12 个测试中校验过唯一性与Layout枚举枚举值说明Theme.DEFAULTdefault默认主题Theme.ALTERNATEalternate交替配色Theme.MOONmoon深色月亮主题Theme.PURPLEpurple紫色主题Theme.SOLARIZEDsolarizedSolarized 配色Theme.BLUE_PLANETbluePlanet蓝行星主题Theme.SATURNsaturn土星主题Theme.KEPLERkepler开普勒主题Playground 默认使用Theme.MARSmars火星主题Theme.DEEP_SPACEdeepSpace深空主题Theme.LASERWAVElaserwave激光波主题Theme.NONEnone无内置主题配合custom_css使用Layout枚举仅两值MODERNmodern默认与CLASSICclassic。源码中所有枚举参数都做了「枚举成员或普通字符串」的双向兼容处理theme theme.value if isinstance(theme, Enum) else theme因此themeTheme.MOON与thememoon完全等价测试test_string_and_enum_produce_identical_output验证了二者生成的 HTML 逐字节一致。交互与显示选项参数默认值说明show_sidebarTrue是否显示侧边栏dark_modeNone初始深色模式状态未设置时跟随系统force_dark_mode_stateNone强制固定为dark或lighthide_dark_mode_toggleFalse是否隐藏深色模式切换按钮hide_test_request_buttonFalse是否隐藏 Test Request 发送请求按钮hide_modelsFalse是否隐藏全部数据模型hide_searchFalse是否隐藏侧边栏搜索框search_hot_keySearchHotKey.K搜索快捷键默认k即 CmdK / CtrlK可选任意单字母document_download_typeDocumentDownloadType.BOTH文档下载类型json、yaml、both、nonehide_download_buttonFalse旧版参数已弃用建议改用document_download_typedefault_open_all_tagsFalse是否默认展开所有标签分组expand_all_model_sectionsFalse是否默认展开所有模型区块expand_all_responsesFalse是否默认展开所有响应区块order_required_properties_firstTrue必填属性是否排在 schema 属性最前order_schema_properties_byalpha属性排序alpha字母序或preserve保持原序hidden_clientsNone隐藏客户端生成器支持{target: bool}字典或字符串列表hide_client_buttonFalse是否隐藏侧边栏和弹窗中的客户端按钮show_developer_toolslocalhost开发者工具可见性always/localhost/neverwith_default_fontsTrue是否使用默认字体Inter 与 JetBrains Mono网络与认证参数默认值说明scalar_js_urlhttps://cdn.jsdelivr.net/npm/scalar/api-reference加载 Scalar 前端 JS 的地址scalar_proxy_urlScalar 代理地址用于绕过浏览器 CORS 限制scalar_favicon_urlFastAPI 官方 favicon浏览器标签页图标base_server_url为所有相对 server 地址统一加前缀serversNoneOpenAPI Server 对象列表如[{url: https://api.example.com, description: Production}]authenticationNone附加认证信息字典如 apiKey、bearer、oauth2persist_authFalse是否将认证凭据持久化到 localStoragecustom_css自定义 CSS 字符串plugin_urlsNoneESM 插件模块 URL 列表在挂载前导入并注册telemetryTrue遥测开关仅记录 API 客户端是否发出过请求agentNoneAgent Scalar 配置AgentScalarConfig(disabledTrue)可整体关闭overridesNone任意附加配置覆盖合并进最终配置对象integrationfastapi集成类型标识写入_integration字段值得注意的是源码只把非默认值写入最终配置test_default_parameters对此有完整断言因此生成的 HTML 中的配置对象足够精简也方便你肉眼核对哪些选项真正生效。验证集成运行测试套件integrations/fastapi目录下带有完善的测试测试说明见 tests/README.mdtest_scalar_fastapi.py对get_scalar_api_reference的单元测试默认参数省略、自定义参数序列化、全部 12 个主题、XSS 防注入等test_integration.pyFastAPI 应用集成测试多端点共存、OpenAPI schema 不受污染、主题/布局/认证等配置生效。两种运行方式任选其一# 方式一官方测试运行脚本推荐 python run_tests.py # 方式二pytest 直接运行 pip install -r tests/requirements.txt pytest tests/ -v集成测试还验证了几个容易被忽视的行为多个/scalar端点不同主题、不同配置可以在同一应用中共存add_scalar_reference挂载的路由不会出现在/openapi.json的paths中传字符串参数与传枚举成员产物完全一致。从 Playground 走向你自己的项目Playground 展示的「安装 → 运行 → 访问 /scalar」三步流程可以无缝迁移到任何 FastAPI 项目pip install scalar-fastapifrom fastapi import FastAPI from scalar_fastapi import add_scalar_reference, Theme app FastAPI(titleMy API) add_scalar_reference(app, themeTheme.DEEP_SPACE) app.get(/hello) def hello(): return {message: world}运行uvicorn main:app --reload后访问/scalar即可获得交互式文档。需要换主题、改布局、加多数据源或接入认证时参考上文参数表逐项传入即可——所有选项都透传到get_scalar_api_reference。若想进一步了解插件的版本演进可查阅 integrations/fastapi/CHANGELOG.md该插件包本身由 pyproject.toml 定义支持 Python 3.9 及以上版本源码含类型标注py.typed类型检查器可直接获得完整提示。【免费下载链接】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),仅供参考
返回列表