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 的官方仓库下载。
相关推荐
带娃的IT创业者3 小时前
第2集:技术选型的智慧:Flask vs FastAPI,GLM-4 vs GPT
python·gpt·flask·fastapi·glm·技术选型
万粉变现经纪人4 天前
如何解决 pip install 安装报错 ImportError: cannot import name ‘xxx’ from ‘yyy’ 问题
python·selenium·测试工具·flask·scikit-learn·fastapi·pip
闲人编程5 天前
2025年,如何选择Python Web框架:Django, Flask还是FastAPI?
前端·后端·python·django·flask·fastapi·web
chao_7895 天前
Union 和 Optional 区别
开发语言·数据结构·python·fastapi
BTU_YC6 天前
Django+FastAPI+Vue微服务架构指南
架构·django·fastapi
Gerlat小智6 天前
【Python精讲 16】实战项目演练(二):用Flask/FastAPI发布你的第一个Web API
python·flask·fastapi
onelafite7 天前
淘宝开放平台拍立淘接口返回参数及调用操作指南
api·fastapi
weixin_421133417 天前
使用 SQLAlchemy 和 Alembic 处理 FastAPI 中的模型变更
fastapi
老坛程序员9 天前
FastAPI WebSocket 由浅入深的开发范例
websocket·网络协议·fastapi
万粉变现经纪人10 天前
如何解决 pip install 安装报错 ModuleNotFoundError: No module named ‘tokenizers’ 问题
python·selenium·测试工具·scrapy·beautifulsoup·fastapi·pip