FastAPI通过Kong API网关访问时openapi.json加载失败求助
解决FastAPI通过Kong网关访问时OpenAPI文档404问题
问题原因
通过Kong访问FastAPI的/docs页面时,页面会请求/openapi.json获取API定义,但由于Kong的路径前缀配置或FastAPI未识别网关后的实际路径,导致该请求无法被正确转发到FastAPI,返回404错误。此外自定义Swagger UI的静态文件路径也可能存在适配问题。
解决方案
1. 为FastAPI设置root_path
FastAPI的root_path参数用于指定应用在反向代理后的根路径,设置后会自动调整所有API文档相关URL的路径:
app = FastAPI( title="XAI_FASTAPI", version=0.1, # 替换为你的Kong路由前缀,例如"/api" root_path="/api" )
如果需要动态适配前缀,可以通过请求对象获取反向代理传递的路径信息:
from fastapi import Request @app.get("/docs", include_in_schema=False) async def custom_swagger_ui_html(request: Request): root_path = request.scope.get("root_path", "") return get_swagger_ui_html( openapi_url=f"{root_path}{app.openapi_url}", title=app.title + " - Swagger UI", oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url, swagger_js_url=f"{root_path}/static/swagger-ui-bundle.js", swagger_css_url=f"{root_path}/static/swagger-ui.css", )
2. 检查Kong路由配置
确保Kong路由规则覆盖所有必要路径:
- 将路由的
paths设置为/{path:*}(匹配所有子路径),或明确包含/docs、/openapi.json、/predict/image等路径 - 确认
strip_path选项处于开启状态(默认开启),Kong会自动移除前缀后将请求转发给FastAPI
3. 配置FastAPI静态文件服务
自定义Swagger UI引用了/static/下的资源,需要挂载静态文件目录:
from fastapi.staticfiles import StaticFiles # 假设静态文件存放在项目根目录的static文件夹中 app.mount("/static", StaticFiles(directory="static"), name="static")
确保static文件夹内存在swagger-ui-bundle.js和swagger-ui.css文件,可从Swagger UI官方资源包中获取对应文件。
4. 验证步骤
- 直接访问FastAPI地址
http://<fastapi-ip>:8000/docs,确认文档正常加载 - 通过Kong访问
http://<kong-ip>:<kong-port>/<prefix>/docs,检查页面是否能正确加载openapi.json
内容的提问来源于stack exchange,提问作者Mohammed Ragab
相关产品推荐
相关产品推荐

