问题背景
FastAPI 默认使用 jsDelivr CDN 加载 Swagger UI 资源文件:
- https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css
- https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js
国外 CDN 在国内访问速度慢,经常加载失败。
解决方案
通过自定义文档路由替换默认 CDN 地址。
实现步骤
1. 导入必要的模块
from fastapi import FastAPI
from fastapi.openapi.docs import get_swagger_ui_html, get_redoc_html
2. 禁用默认文档路由
app = FastAPI(
title="FastAPI Backend Service",
docs_url=None, # 禁用默认 Swagger UI
redoc_url=None, # 禁用默认 ReDoc
)
3. 创建自定义文档路由
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
"""自定义 Swagger UI,使用自己的 CDN"""
return get_swagger_ui_html(
openapi_url=app.openapi_url,
title=f"{app.title} – Swagger UI",
swagger_js_url="https://your-cdn.com/swagger-ui-bundle.js",
swagger_css_url="https://your-cdn.com/swagger-ui.css",
)
@app.get("/redoc", include_in_schema=False)
async def custom_redoc_html():
"""自定义 ReDoc,使用自己的 CDN"""
return get_redoc_html(
openapi_url=app.openapi_url,
title=f"{app.title} – ReDoc",
redoc_js_url="https://your-cdn.com/redoc.standalone.js",
)
CDN 选择方案
方案1:自建 CDN(推荐)
swagger_js_url="https://static.xutongbao.top/py/swagger-ui-bundle.js"
swagger_css_url="https://static.xutongbao.top/py/swagger-ui.css"
redoc_js_url="https://static.xutongbao.top/py/redoc.standalone.js"
方案2:国内公共 CDN
unpkg.com(有国内节点)
swagger_js_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js"
swagger_css_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css"
redoc_js_url="https://unpkg.com/redoc@latest/bundles/redoc.standalone.js"
BootCDN
swagger_js_url="https://cdn.bootcdn.net/ajax/libs/swagger-ui/5.10.5/swagger-ui-bundle.min.js"
swagger_css_url="https://cdn.bootcdn.net/ajax/libs/swagger-ui/5.10.5/swagger-ui.min.css"
redoc_js_url="https://cdn.bootcdn.net/ajax/libs/redoc/2.1.3/redoc.standalone.js"
核心要点
效果
- ✅ 加载速度显著提升
- ✅ 不依赖国外 CDN
- ✅ 完全控制资源文件版本
- ✅ 可随时切换 CDN 地址
完整代码示例
from fastapi import FastAPI
from fastapi.openapi.docs import get_swagger_ui_html, get_redoc_html
app = FastAPI(
title="My API",
docs_url=None,
redoc_url=None,
)
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
return get_swagger_ui_html(
openapi_url=app.openapi_url,
title=f"{app.title} – Swagger UI",
swagger_js_url="https://your-cdn.com/swagger-ui-bundle.js",
swagger_css_url="https://your-cdn.com/swagger-ui.css",
)
@app.get("/redoc", include_in_schema=False)
async def custom_redoc_html():
return get_redoc_html(
openapi_url=app.openapi_url,
title=f"{app.title} – ReDoc",
redoc_js_url="https://your-cdn.com/redoc.standalone.js",
)
访问 http://localhost:8000/docs 即可看到使用自定义 CDN 的 Swagger UI 文档。


