You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OpenAPI 3中additionalProperties的属性键可设置哪些限制?

关于OpenAPI中限制additionalProperties属性键的问题

OpenAPI 3.0的局限

在OpenAPI 3.0版本里,additionalProperties仅能控制属性值的结构,没有直接语法约束对象属性键的规则——虽然你能用minProperties/maxProperties限制城市的数量,但没法对键的长度、格式这类要求做编码实现。这种情况下,只能在cities字段的description里明确标注规则,比如修改描述为:

description: A mapping of city names to data about those cities. City names must be 1-100 characters long.

OpenAPI 3.1的解决方案

如果你的API文档可以升级到OpenAPI 3.1(它兼容JSON Schema 2020-12特性),就能用propertyNames关键字实现对属性键的限制,完全不需要修改现有CityData结构。具体写法如下:

components:
  schemas:
    CityData:
      type: object
      properties:
        population:
          type: integer
        is_capital:
          type: boolean
    Country:
      type: object
      properties:
        name:
          type: string
        cities:
          type: object
          description: A mapping of city names to data about those cities. City names must be 1-100 characters long.
          additionalProperties:
            $ref: '#/components/schemas/CityData'
          # 新增propertyNames约束键的长度
          propertyNames:
            type: string
            minLength: 1
            maxLength: 100

propertyNames会作用于对象的所有属性键,确保每个城市名称的长度都符合1-100字符的要求。

总结:如果使用OpenAPI 3.0,只能靠文字描述约定规则;若能升级到3.1,就可以通过propertyNames编码实现该限制。

内容的提问来源于stack exchange,提问作者Mitch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 00:27:42