0%

FastAPI自学教程(91) - Swagger UI配置指南

1.基础用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from fastapi import FastAPI
from fastapi.openapi.docs import get_swagger_ui_html

app = FastAPI()

@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="https://cdn.example.com/swagger-ui-bundle.js",
swagger_css_url="https://cdn.example.com/swagger-ui.css",
swagger_favicon_url="/static/favicon.png"
)
  • 使用get_swagger_ui_html函数生成自定义Swagger UI页面
  • 核心配置参数:
    • openapi_url:OpenAPI规范文件路径(默认/openapi.json
    • swagger_js_url:Swagger UI的JavaScript文件地址
    • swagger_css_url:Swagger UI的CSS文件地址
    • swagger_favicon_url:页面图标地址

流程图展示自定义UI加载流程:

graph TD
    A[访问/docs端点] --> B[调用get_swagger_ui_html]
    B --> C[加载JS/CSS资源]
    C --> D[请求/openapi.json]
    D --> E[渲染交互式UI]

2.高级配置技巧

2.1 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()
  • 必须保留默认OAuth2重定向路径/oauth2-redirect
  • 支持通过init_oauth参数配置OAuth2初始化信息

2.2 本地资源托管

1
app.mount("/static", StaticFiles(directory="static"), name="static")
  • 本地文件目录结构要求:
    1
    2
    3
    4
    5
    6
    project/
    ├── static/
    │ └── swagger-ui/
    │ ├── swagger-ui-bundle.js
    │ ├── swagger-ui.css
    │ └── favicon.png
  • 优势:避免CDN依赖,提升加载速度

3.生产环境建议

  1. 安全加固

    1
    app = FastAPI(docs_url=None)  # 禁用默认文档
    • 通过Nginx限制/docs端点的IP白名单访问
  2. 版本控制

    1
    swagger_js_url="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.9.0/swagger-ui-bundle.js"
    • 指定Swagger UI版本避免更新导致兼容问题
  3. 性能优化

    • 启用Brotli压缩静态资源(减少40%-70%体积)
    • 设置缓存头:Cache-Control: max-age=31536000
  4. 监控告警

    • 记录文档访问日志
    • 配置资源加载失败告警机制

4.注意事项

  • 修改swagger_ui_oauth2_redirect_url路径会破坏OAuth2流程
  • 使用swagger_ui_parameters可调整UI布局和交互参数
  • 开发环境建议保留热重载功能,生产环境必须关闭调试模式

完整实现参考:
FastAPI官方Swagger UI配置文档
测试命令示例:

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

# 访问自定义文档
xdg-open http://localhost:8000/docs