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 的官方仓库下载。
相关推荐
Ares-Wang15 小时前
FastAPI 数据验证 Pydantic Flask 用 WTForms
python·flask·fastapi
曲幽16 小时前
FastAPI自动生成的API文档太丑?我花了一晚上把它改成了客户愿意付费的样子
python·fastapi·web·swagger·openapi·scalar·docs
PieroPc2 天前
一个功能强大的 Web 端标签设计和打印工具,支持服务器端直接打印到局域网打印机。Fastapi + html
前端·html·fastapi
别抢我的锅包肉2 天前
FastAPI + Vue3 + Vite 跨域报错全解:从 `Access-Control-Allow-Origin missing` 到彻底修复
中间件·状态模式·fastapi
Chase_______2 天前
【FastAPI】内网/离线环境docs文档无法显示的解决方案
fastapi
小李云雾2 天前
FastAPI 后端开发:文件上传 + 表单提交
开发语言·python·lua·postman·fastapi
曲幽2 天前
告别手写 API 胶水代码:FastAPI 与 Vue 的“契约自动机” OpenAPI 实战
python·typescript·vue·fastapi·web·swagger·openapi·codegen
2401_835792544 天前
FastAPI 速通
windows·python·fastapi
海市公约4 天前
FastAPI入门实战:从零搭建到核心功能详解
fastapi·后端入门·异步编程·路由管理·python web开发·api设计·pydantic数据验证
曲幽4 天前
FastAPI + Vue 前后端分离实战:我的项目结构“避坑指南”
python·vue·fastapi·web·vite·proxy·cors·env