如何在OpenAPI中实现满足双需求的原始类型组件Schema复用
问题:打造可复用单原始类型键值对Schema的痛点
现有两种实现方案
方案1:嵌套在单键对象中
portComponent: type: object properties: port: type: integer minimum: 1 maximum: 65535 required: - port
方案2:直接定义原始值
portComponent: type: integer minimum: 1 maximum: 65535
核心需求
- 原始值必须使用固定键名:减少出错概率,同时让代码生成器为每个键值对生成独立代码类(仅方案1满足此要求)
- 可灵活指定组件是否必填:方案1只能通过
allOf标记整个组件为必填,无法设为可选;方案2虽能在外部通过required控制必填性,但会导致代码生成失效,且无法强制键名统一
换角度提问
如何将组件Schema(可选/必填)添加到另一个组件中,既不嵌套到新属性里,也不用allOf等方式强制其必填?
测试环境与示例说明
使用openapitools/openapi-generator-cli:v7.0.0针对Python-Flask进行测试,最小示例如下:
openapi: 3.0.3 info: version: 1.0.0 title: sandbox tags: - name: Information description: System information paths: /portValueOnly: get: operationId: get_port_value_only tags: - Information responses: 200: description: Provides port content: application/json: schema: $ref: '#/components/schemas/portComponent' /portWrapped: get: operationId: get_port_wrapped tags: - Information responses: 200: description: Provides port content: application/json: schema: type: object properties: port: $ref: '#/components/schemas/portComponent' /information: get: operationId: get_all_system_information tags: - Information responses: 200: description: Provides all system information content: application/json: schema: $ref: '#/components/schemas/systemInformation' /character: get: operationId: get_character tags: - Information responses: 200: description: Provides a character content: application/json: schema: $ref: '#/components/schemas/enumComponent' components: schemas: systemInformation: type: object properties: character: $ref: '#/components/schemas/enumComponent' port: $ref: '#/components/schemas/portComponent' enumComponent: type: string enum: - "a" - "b" portComponent: type: integer minimum: 1 maximum: 65535 thingWithTypo: type: object properties: pord: $ref: '#/components/schemas/portComponent'
生成结果说明
- 路由
/portWrapped会生成get_port_wrapped200_response.py,但其他组件中引用的portComponent会生成原始类型,此情况已理解并接受,将改用/portValueOnly这类直接返回原始组件的路由规避。 - 此前无包装原始值组件(如枚举)的代码生成错误(例如生成
NUMBER_'a' = 'a')已通过PR #16576修复。
内容的提问来源于stack exchange,提问作者Nesuma
相关产品推荐
相关产品推荐

