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 的官方仓库下载。
相关推荐
坚定信念,勇往无前13 小时前
python的fastapi+uvicorn的linux离线部署
fastapi
yuezhilangniao16 小时前
FastAPI-Scaff脚手架项目完整配置指南
fastapi
Hi_kenyon17 小时前
FastAPI+VUE3创建一个项目的步骤模板(三)
python·fastapi
Hi_kenyon20 小时前
FastAPI+VUE3创建一个项目的步骤模板(一)
python·fastapi
计算衎2 天前
FastAPI后端和VUE前端的数据交互原理详解
前端·vue.js·fastapi
IMPYLH2 天前
Lua 的 Debug(调试) 模块
开发语言·笔记·python·单元测试·lua·fastapi
@我本楚狂人2 天前
Python MCP实战:构建 FastAPI 服务端与客户端示例&MCP客户端调用
开发语言·python·fastapi
绝不收费—免费看不了了联系我2 天前
Fastapi的单进程响应问题 和 解决方法
开发语言·后端·python·fastapi
Non-existent9872 天前
Flutter + FastAPI 30天速成计划自用并实践-第10天-组件化开发实践
android·flutter·fastapi
闲人编程3 天前
FastAPI性能优化技巧
后端·python·性能优化·fastapi·性能·codecapsule