0%

FastAPI自学教程(90) - 自定义文档UI静态资源

1.基础用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from fastapi import FastAPI
from fastapi.openapi.docs import get_swagger_ui_html, get_redoc_html
from fastapi.staticfiles import StaticFiles

app = FastAPI(docs_url=None, redoc_url=None) # 禁用默认文档端点

# 挂载本地静态资源目录
app.mount("/static", StaticFiles(directory="static"), name="static")

@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui():
return get_swagger_ui_html(
openapi_url="/openapi.json",
title="API Docs",
swagger_js_url="/static/swagger-ui/swagger-ui-bundle.js",
swagger_css_url="/static/swagger-ui/swagger-ui.css",
swagger_favicon_url="/static/swagger-ui/favicon.png"
)
  • 通过docs_url=None禁用默认Swagger UI,防止与自定义路由冲突
  • 使用app.mount()挂载本地静态资源目录,文件结构需包含swagger-ui-bundle.js等核心文件
  • 流程图展示请求处理流程:
    graph TD
      A[请求/docs] --> B[自定义路由处理]
      B --> C[加载本地JS/CSS]
      C --> D[渲染Swagger UI]
      D --> E[请求/openapi.json]

2.自托管资源配置

2.1 静态文件结构

1
2
3
4
5
6
7
project/
├── app.py
└── static/
└── swagger-ui/
├── swagger-ui.css
├── swagger-ui-bundle.js
└── favicon.png
  • 必须包含Swagger UI的三大核心文件:CSS、JS Bundle和图标
  • 推荐使用swagger-ui-distnpm包的发行版文件保证兼容性

2.2 OAuth2集成

1
2
3
@app.get(app.swagger_ui_oauth2_redirect_url, include_in_schema=False)
async def swagger_ui_redirect():
return get_swagger_ui_oauth2_redirect_html()
  • 该路由用于处理Swagger UI与OAuth2提供商的认证回调
  • 需保持默认路径/oauth2-redirect,否则会破坏OAuth流程

3.高级定制技巧

3.1 HTML模板修改

1
2
html = get_swagger_ui_html(...)
html = html.replace('<title>Swagger UI</title>', '<title>定制文档</title>')
  • 通过字符串替换可修改页面标题、添加自定义CSS/JS
  • 支持插入品牌Logo和监控脚本等定制内容

3.2 CDN切换方案

1
swagger_js_url="https://cdn.example.com/swagger-ui-bundle.js"
  • 可替换unpkg为私有CDN提升加载速度
  • 需确保CDN版本与本地FastAPI版本兼容

4.生产环境建议

  1. 安全加固

    • 通过Nginx限制/docs端点的IP白名单访问
    • 禁用开发环境专用的swagger_ui_parameters调试参数
  2. 版本控制

    1
    app = FastAPI(openapi_url="/v2/openapi.json")

    为OpenAPI规范添加版本路径,避免客户端缓存冲突

  3. 性能优化

    • 启用Brotli压缩静态资源
    • 设置长期缓存头:Cache-Control: max-age=31536000
  4. 监控告警

    • 记录/docs端点的访问日志
    • 配置静态资源加载失败报警

完整实现参考:
FastAPI官方自定义文档指南
本地资源部署示例
测试命令示例:

1
2
3
4
5
# 本地资源校验
curl -I http://localhost:8000/static/swagger-ui/swagger-ui-bundle.js

# 文档访问测试
xdg-open http://localhost:8000/docs