如何在 FastAPI 中使用本地资源自定义 Swagger UI
要自定义 FastAPI 中的 Swagger UI,且使用本地资源来代替 CDN。只是需要稍微修改一下。
修改后的代码:
步骤:
- 挂载本地静态文件目录:我们将本地的 Swagger UI 资源文件(如
.js
,.css
,favicon.png
等)放置在项目的一个目录中(例如:static/swagger-ui
)。 - 自定义 Swagger UI 页面:您可以通过 FastAPI 的
get_swagger_ui_html()
方法来加载本地的 Swagger UI 页面。
修改后的代码:
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.openapi.docs import get_swagger_ui_html
app = FastAPI(
docs_url=None, # 禁用默认的 Swagger UI 地址
redoc_url=None # 禁用 ReDoc 默认地址
)
# Step 1: Mount the static directory for Swagger UI resources
app.mount("/static", StaticFiles(directory="static"), name="static")
# Step 2: Define custom Swagger UI route
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui():
return get_swagger_ui_html(
openapi_url="/openapi.json", # 指定 OpenAPI 文档路径
title="API Docs", # 自定义页面标题
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" # 本地 favicon 图标
)
解释:
-
禁用默认的 Swagger UI:
docs_url=None, # 禁用默认的 Swagger UI 地址 redoc_url=None # 禁用 ReDoc 默认地址
通过设置
docs_url=None
和redoc_url=None
,您禁用了 FastAPI 默认提供的 Swagger UI 和 ReDoc 文档路径。 -
挂载静态文件目录:
app.mount("/static", StaticFiles(directory="static"), name="static")
这行代码将本地
static
目录挂载为静态文件服务。Swagger UI 资源文件应该放在static/swagger-ui
目录下。 -
自定义 Swagger UI 页面:
@app.get("/docs", include_in_schema=False) async def custom_swagger_ui(): return get_swagger_ui_html( openapi_url="/openapi.json", title="API Docs", swagger_js_url="/static/swagger-ui/swagger-ui-bundle.js", swagger_css_url="/static/swagger-ui/swagger-ui.css", swagger_favicon_url="/static/swagger-ui/favicon.png" )
get_swagger_ui_html()
是 FastAPI 提供的函数,用于生成 Swagger UI 的 HTML 页面。您可以在其中自定义:openapi_url
:指定您的 OpenAPI 文档 URL。swagger_js_url
、swagger_css_url
、swagger_favicon_url
:指定 Swagger UI 需要的本地资源文件路径。
本地文件结构:
您的文件夹结构应该如下:
project/
│
├── app.py # FastAPI 代码
├── static/
│ └── swagger-ui/
│ ├── swagger-ui.css
│ ├── swagger-ui-bundle.js
│ ├── swagger-ui-standalone-preset.js
│ └── favicon.png
访问 Swagger UI:
- 启动应用后,访问
http://127.0.0.1:8000/docs
,您应该可以看到加载了本地资源的 Swagger UI 页面,而不再依赖外部 CDN。
这样,您就可以使用 FastAPI 提供的本地资源来定制 Swagger UI 了。