fastapi 使用本地资源自定义swagger文档

复制代码
# /docs - Swagger UI 交互式文档
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
    return get_swagger_ui_html(
        openapi_url=app.openapi_url,  # 指向 OpenAPI JSON 规范
        title=app.title + " - Swagger UI",  # 页面标题
        oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,  # OAuth2 回调
        swagger_js_url="/static/swagger-ui/swagger-ui-bundle.js",  # 自定义 JS
        swagger_css_url="/static/swagger-ui/swagger-ui.css",  # 自定义 CSS
        swagger_favicon_url="/static/swagger-ui/favicon.png",  # 自定义图标
    )
# OAuth2 重定向端点
# 作用:处理 OAuth2 认证的回调  完成 Swagger UI 的认证流程
@app.get(app.swagger_ui_oauth2_redirect_url, include_in_schema=False)
async def swagger_ui_redirect():
    return get_swagger_ui_oauth2_redirect_html()

# /redoc - ReDoc 文档 适合阅读
@app.get("/redoc", include_in_schema=False)
async def redoc_html():
    return get_redoc_html(
        openapi_url=app.openapi_url,
        title=app.title + " - ReDoc",
        redoc_js_url="/static/redoc/redoc.standalone.js",
        redoc_favicon_url="/static/redoc/favicon.png",
        with_google_fonts=False  # 禁用 Google 字体(国内访问友好)
    )

include_in_schema=False 的重要性

这个参数表示这些端点不会出现在 API 文档本身中,如果没有这个参数,会出现递归引用的问题。

你需要在 static 目录下放置相应的文件:

复制代码
static/
├── swagger-ui/
│   ├── swagger-ui-bundle.js
│   ├── swagger-ui.css
│   └── favicon.png
└── redoc/
    ├── redoc.standalone.js
    └── favicon.png
复制代码
这些文件可以从 Swagger UI 和 ReDoc 的官方仓库下载。
相关推荐
肥肠可耐的西西公主1 天前
后端(FastAPI)学习笔记(CLASS 3):Tortoise ORM
笔记·学习·fastapi
onelafite2 天前
小红书笔记评论一键获取,实时查看作品数据
api·fastapi
shao9185163 天前
Gradio全解11——Streaming:流式传输的视频应用(2)——Twilio:网络服务提供商
fastapi·handler·stun·turn·ice·twillo
枫叶V3 天前
用 FastAPI 实现大文件分片上传与断点续传(含可运行示例与客户端脚本,仅供参考)
python·fastapi
蓝倾6 天前
利用API接口合规获取淘宝店铺所有商品实战案例(2025年最新版)
api·fastapi
肥肠可耐的西西公主7 天前
后端(fastAPI)学习笔记(CLASS 1):扩展基础
笔记·学习·fastapi
红鼻子时代8 天前
Day5-中间件与请求处理
中间件·fastapi·后端开发
蓝倾9 天前
京东商品属性API数据解析:颜色、尺寸与材质
api·fastapi
CodeDevMaster10 天前
使用Transformers、ChatGLM3项目、创建FastAPI应用等方式部署调用ChatGLM3-6B模型
llm·fastapi·chatglm (智谱)