在互聯網環境中,只要 啟動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 會從本地加載資源,無需外網。