Flask+Connexion+Swagger UI启动异常:访问/api/ui遭404错误
问题解决:Connexion 3.x + Flask Swagger UI 404错误
问题根源
Connexion 3.x版本对Swagger UI的默认配置和路由挂载逻辑做了调整,你当前的代码没有正确匹配OpenAPI配置中的服务路径,也未显式指定Swagger UI的挂载路径,导致访问/api/ui时出现404。
解决方案
修改app/__init__.py中的add_api调用,补充必要的配置参数:
from connexion import FlaskApp from flask.app import Flask from pathlib import Path BASE_DIR = Path(__file__).parent.resolve() def create_app() -> Flask: flask_app: FlaskApp = FlaskApp(__name__) app: Flask = flask_app.app # 配置API基础路径和Swagger UI路径 flask_app.add_api( "openapi.yaml", base_path="/api", # 匹配openapi.yaml中servers.url的配置 swagger_ui=True, # 显式启用Swagger UI swagger_ui_path="/ui" # 指定Swagger UI挂载路径 ) return app
验证步骤
- 重启Flask服务:
flask run --debug
- 访问Swagger UI:
http://127.0.0.1:5000/api/ui,此时应该能正常加载界面。 - 测试API接口:访问
http://127.0.0.1:5000/api/hello,应返回Hello, world!。
说明
base_path="/api":确保API路由与openapi.yaml中servers节点配置的/api路径一致,避免路由不匹配。swagger_ui_path="/ui":将Swagger UI挂载到/api/ui,完全符合你预期的访问地址。- Connexion 3.x默认的Swagger UI路径为
/swagger/ui,如果不指定swagger_ui_path,也可以通过这个路径访问,但显式配置更贴合你的需求。
内容的提问来源于stack exchange,提问作者dmjy
相关产品推荐
相关产品推荐

