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 的官方仓库下载。
相关推荐
小庄梦蝶3 小时前
关于fastapi使用注意点
fastapi
hudawei9964 小时前
Flask 与 FastAPI 对比分析
python·flask·fastapi
你喜欢喝可乐吗?20 小时前
FastAPI 入门笔记
笔记·fastapi
一尘之中1 天前
Ubuntu 22.04 上 FastAPI 的完整安装与问题解决指南
ubuntu·fastapi·ai写作
PieroPc1 天前
用FastAPI 后端 和 Vue3 前端写一个博客系统 例
前端·vue·fastapi
小北方城市网1 天前
Python FastAPI 异步性能优化实战:从 1000 QPS 到 1 万 QPS 的踩坑之路
大数据·python·性能优化·架构·fastapi·数据库架构
simon_skywalker1 天前
FastAPI实战笔记(七)集成 NoSQL数据库
nosql·fastapi
一碗面4212 天前
不用第三方 API!FastAPI + PaddleOCR 自建身份证 OCR 服务实战
ocr·fastapi
Psycho_MrZhang2 天前
Django/Flask/FastAPI简要对比分析
django·flask·fastapi
曲幽3 天前
FastAPI + SQLite:从基础CRUD到安全并发的实战指南
python·sqlite·fastapi·web·jwt·form·sqlalchemy·oauth2