怎么让接口文档不和代码脱节?OpenAPI 文档能不能自动生成?校验规则会不会进文档?这篇用 apispec 与 flask-smorest 真的生成一份文档,并用校验器检查它是否合法。
顶层键: ['paths', 'info', 'openapi', 'components']
paths: ['/users/{uid}']
components.schemas: ['User']
User 模型生成的 schema: {"type": "object", "properties": {"id": {"type": "integer", "readOnly": true}, "name": {"type": "string", "minLength": 1, "maxLength": 20}, "age": {"type": "integer", "minimum": 0, "maximum": 150}}, "required": ["name"], "additionalProperties": false}
视图 docstring 里引用 "UserSchema" 被解析成: {'$ref': '#/components/schemas/User'}
Flask 的 <int:uid> 路由被转成 OpenAPI 的路径: /users/{uid}
openapi-spec-validator:文档合法上一篇:ETag API 缓存;下一篇:Marshmallow 序列化。
name: {'type': 'string', 'minLength': 1, 'maxLength': 20} | age: {'type': 'integer', 'minimum': 0, 'maximum': 150} | id: {'type': 'integer', 'readOnly': True}
required: ['name']GET /openapi.json → 200 | openapi = 3.0.3 | paths = ['/users/'] /users/ 下的方法: ['get', 'post'] | POST 的响应码: ['422', '201', 'default'] 文档合法 GET /docs(Swagger UI)→ 200 text/html | 页面里引用的脚本源: True (Swagger UI 的 JS 来自 CDN——离线环境或有内容安全策略的站点要自己托管,本篇没有在浏览器里渲染它)
POST {name:"", age:200} → 422 {"code": 422, "errors": {"json": {"age": ["Must be greater than or equal to 0 and less than or equal to 150."], "name": ["Length must be between 1 and 20."]}}, "status": "Unprocessable Entity"}
多余字段 extra → 422 {'json': {'extra': ['Unknown field.']}}
合法 → 201 {'age': 5, 'id': 2, 'name': 'bob'}
文档里写了 422 响应吗: Truerequired 变成: ['age', 'name'] (之前是 ['name']) 手写的 YAML docstring 不会自动跟着变——这部分仍要靠人维护