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 的官方仓库下载。
相关推荐
青衫客3614 小时前
从零实现多智能体 Runtime(一):系统架构、状态机与任务编排设计
agent·fastapi
曲幽17 小时前
FastApiAdmin 后端接口开发好了,前端管理界面怎么调用与显示?
python·vue3·api·fastapi·web·ant design·view·menu·frontend
dinl_vin19 小时前
FastAPI 系列·(七):Redis 集成——缓存、分布式锁与 Session 管理
redis·缓存·fastapi
还是鼠鼠19 小时前
AI掘金头条新闻系统 (Toutiao News)-封装通用成功响应格式
数据库·后端·python·fastapi·web
dinl_vin1 天前
FastAPI 系列·(三):依赖注入——用 Depends 构建分层架构
架构·fastapi
XGeFei2 天前
【Fastapi学习笔记(1)】—— Pydantic模型、依赖注入、请求头-Cookie、响应头
笔记·学习·fastapi
还是鼠鼠2 天前
AI掘金头条新闻系统 (Toutiao News)-用户注册-生成Token
后端·python·mysql·fastapi·web
毋语天2 天前
FastAPI 进阶实战:请求体、文件上传、响应模型与数据校验
python·fastapi·api开发·数据校验·pydantic
还是鼠鼠2 天前
AI掘金头条新闻系统 (Toutiao News)-用户注册-创建用户
后端·python·mysql·fastapi·web
shangxianjiao3 天前
fastapi
python·fastapi