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 的官方仓库下载。
相关推荐
绘梨衣5479 小时前
Docker+FastAPI+MySQL 项目部署报错汇总
mysql·docker·fastapi
Muyuan199814 小时前
27.RAG 系统中的上下文充分性判断:从 Chunk 数量、FAISS 距离到 LLM Relevance Gate
python·django·pdf·fastapi·faiss
曲幽18 小时前
FastAPI 少有人提的实用技巧:把 Depends 依赖提到路由层,代码少写60%
python·fastapi·web·routes·depends·prefix·apiroute
.柒宇.20 小时前
AI掘金头条项目部署实践指南
linux·运维·python·fastapi
风流 少年21 小时前
Python Web框架:FastAPI
前端·python·fastapi
iuu_star1 天前
Vue+FastAPI 项目宝塔Linux部署指南
linux·运维·fastapi
.柒宇.1 天前
AI掘金头条项目 Docker Compose 部署完整教程(附踩坑记录)
运维·后端·python·docker·容器·fastapi
曲幽2 天前
FastAPI 生产环境静态文件完全指南:从 /favicon.ico 404 到 HSTS 混合内容,一次全根治
python·fastapi·web·static·media·404·hsts·favicon·url_for
码界筑梦坊2 天前
113-基于Python的国际超市电商销售数据可视化分析系统
开发语言·python·信息可视化·毕业设计·fastapi
.柒宇.2 天前
AI 掘金头条项目-用户模块、收藏模块以及Redis和调用大模型实现
redis·python·fastapi·千问·qwen大模型