使用Flasgger定义模型并验证端点时出现KeyError: 'definitions'求助
问题原因分析
出现KeyError: 'definitions'的核心原因是OpenAPI规范的definitions被错误放置到了Flasgger的配置字典中,而非OpenAPI模板结构里:
- Flasgger的
swagger_config参数用于配置自身运行逻辑(如UI资源路径、spec端点等),不会被当作OpenAPI规范的一部分解析; definitions属于OpenAPI 2.0规范的顶层节点,必须放在template字典中,才能被验证逻辑识别到。
另外,请求体schema的写法存在问题:直接在包含$ref的对象中添加required无效——$ref会覆盖同一层级的其他属性,验证逻辑无法读取到required规则。
解决方案
1. 移动definitions到template中
修改app/__init__.py,将swagger_config中的definitions节点移至template字典:
template = { "swagger": "2.0", "info": { "title": "Test App", }, "basePath": "/api/v1", "schemes": ["http", "https"], # 把definitions放到template里 "definitions": { "User": { "type": "object", "properties": { "id": {"type": "integer", "description": "UserId"}, "email": { "type": "string", "description": "john.doe@abc123.com", }, "first_name": {"type": "string", "description": "John"}, "last_name": {"type": "string", "description": "Doe"}, }, # 直接在这里定义必填字段,避免后续重复 "required": ["email"] } }, } swagger_config = { "headers": [], "specs": [ { "endpoint": "apispec", "route": "/apispec.json", } ], "static_url_path": "/flasgger_static", "swagger_ui": True, "specs_route": "/", "swagger_ui_bundle_js": "//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js", "swagger_ui_standalone_preset_js": "//unpkg.com/swagger-ui-dist@3/swagger-ui-standalone-preset.js", "jquery_js": "//unpkg.com/jquery@2.2.4/dist/jquery.min.js", "swagger_ui_css": "//unpkg.com/swagger-ui-dist@3/swagger-ui.css", # 移除这里的definitions }
2. 修正请求体schema的写法
由于$ref会覆盖同层级属性,若必填字段已在User定义中声明,直接简化schema即可:
user_create_swag = { "tags": ["Accounts"], "parameters": [ { "name": "body", "in": "body", "required": True, # 直接引用定义好的User,必填规则已在template的User中声明 "schema": {"$ref": "#/definitions/User"}, }, ], "responses": { "200": { "description": "The user inserted in the database", "schema": {"$ref": "#/definitions/User"}, } }, }
如果需要在该请求中额外增加必填字段(比如除了email还要求first_name),则用allOf组合规则:
"schema": { "allOf": [ {"$ref": "#/definitions/User"}, {"required": ["email", "first_name"]} ] }
3. 验证修复效果
重启服务后,再次发送curl请求:
curl -X 'POST' \ 'http://127.0.0.1:5000/api/v1/accounts/users' \ -H 'accept: application/json' \ -H 'Content-Type: application/json' \ -d '{ "email": "test@example.com", "first_name": "John", "last_name": "Doe" }'
此时验证逻辑会正确识别User定义,不会再触发KeyError,同时会校验必填字段email是否存在。
内容的提问来源于stack exchange,提问作者luisf
相关产品推荐
相关产品推荐

