在互联网环境中,只要 启动FastAPI 服务运行在本地机器上,访问 http://localhost:8000/docs
(Swagger UI)就可以访问到Swagger界面,但是在完全离线环境(无外网)下如何访问Swagger页面呢?
默认情况下,Swagger UI 会从外部 CDN 加载 CSS 和 JavaScript 文件(如 cdn.jsdelivr.net
)。若机器完全无法访问外网,会导致 Swagger UI 样式丢失。
解决方法:配置 FastAPI 使用本地资源。
下载 Swagger UI 资源
-
从 Swagger UI GitHub 下载最新版本,解压后找到
dist
目录。 -
将
dist
目录中的以下文件复制到 FastAPI 项目的static/swagger
目录:-
swagger-ui-bundle.js
-
swagger-ui.css
-
favicon-32x32.png
(可选)
-
修改 FastAPI 配置
重写 Swagger UI 的 HTML 模板,指向本地资源:
from fastapi import FastAPI
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.staticfiles import StaticFilesapp = FastAPI(docs_url=None) # 禁用默认的 Swagger UI
app.mount("/static", StaticFiles(directory="static"), name="static")@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():return get_swagger_ui_html(openapi_url=app.openapi_url,title="API Docs",swagger_js_url="/static/swagger/swagger-ui-bundle.js",swagger_css_url="/static/swagger/swagger-ui.css",)
your_project/
├── main.py
└── static/└── swagger/├── swagger-ui-bundle.js├── swagger-ui.css└── favicon-32x32.png
验证访问
重启服务后,访问 http://localhost:8000/docs
,Swagger UI 会从本地加载资源,无需外网。