Skip to main content

遇到错误

fastapi swagger-ui 白屏

错误信息

Failed to load resource: net::ERR_CONNECTION_RESET
swagger-ui-bundle.js:1 Failed to load resource: net::ERR_CONNECTION_RESET
docs:15 Uncaught ReferenceError: SwaggerUIBundle is not defined
at docs:15

相关问题:#2759#2735

错误原因

fastapi的swagger样式文件采用了jsdelivr cdn,然而国内经常无法访问这个cdn

解决方法

根据官方文档将文档资源改成离线模式,参照这里或者这里所指示的,采用离线的swagger jscss文件

# redoc可以到 https://unpkg.com/ 这个cdn网站找
https://unpkg.com/browse/redoc@2.0.0-rc.58/bundles/
https://unpkg.com/browse/redoc@2.0.0-rc.58/bundles/redoc.standalone.js

https://unpkg.com/redoc@2.0.0-rc.58/bundles/redoc.standalone.js

# swagger 可以到官网
https://petstore.swagger.io/
# 修复
from fastapi.staticfiles import StaticFiles
from fastapi.openapi.docs import (
get_redoc_html,
get_swagger_ui_html,
get_swagger_ui_oauth2_redirect_html,
)

app = FastAPI(docs_url=None, redoc_url=None)
app.mount("/static", StaticFiles(directory="static"), name="static")

# 将 /docs 重置到离线
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
return get_swagger_ui_html(
openapi_url=app.openapi_url,
title=app.title + " - Swagger UI",
oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,
swagger_js_url="/static/swagger-ui-bundle.js",
swagger_css_url="/static/swagger-ui.css",
)


# swagger 验证问题
@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 重置到离线
@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.standalone.js",
)

解决方法

等待官方修复这个问题,已经有相关PR提交,不过等了半年没有动静

解决方法

修改fastapi实例上swagger的相关文件指向

from fastapi import applications
from fastapi.openapi.docs import get_swagger_ui_html

def swagger_monkey_patch(*args, **kwargs):
"""
Wrap the function which is generating the HTML for the /docs endpoint and
overwrite the default values for the swagger js and css.
"""
return get_swagger_ui_html(
*args,
**kwargs,
swagger_js_url="https://cdn.jsdelivr.net/npm/swagger-ui-dist@3.29/swagger-ui-bundle.js",
swagger_css_url="https://cdn.jsdelivr.net/npm/swagger-ui-dist@3.29/swagger-ui.css")

# Actual monkey patch
applications.get_swagger_ui_html = swagger_monkey_patch

# Your normal code ...
app = FastAPI()