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

基于路径参数的OpenAPI请求JSON Schema条件校验可行性咨询

基于路径参数的请求体校验实现方案

完全可行,你可以通过OpenAPI 3.1+的上下文感知条件校验结合JSON Schema来实现需求——单纯的JSON Schema本身无法访问请求路径参数,但OpenAPI在JSON Schema基础上扩展了请求上下文的访问能力,能关联路径参数和请求体的校验规则。

具体实现步骤

  1. 定义路径参数的枚举范围:明确允许的settingId值,既提升文档可读性,也为后续校验提供明确的匹配目标。
  2. 在请求体Schema中使用oneOf+条件判断:通过OpenAPI的$request变量引用路径参数,为每个settingId指定对应的value校验规则。

完整OpenAPI示例

openapi: 3.1.0
paths:
  /settings/{settingId}:
    put:
      parameters:
        - name: settingId
          in: path
          required: true
          schema:
            type: string
            enum: [eth_enable, max_retries, api_key]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                value: {}
              required: [value]
              oneOf:
                # 当settingId为eth_enable时,value必须是布尔值
                - if:
                    properties:
                      $request.path.settingId:
                        const: eth_enable
                  then:
                    properties:
                      value:
                        type: boolean
                # 当settingId为max_retries时,value是1-10的整数
                - if:
                    properties:
                      $request.path.settingId:
                        const: max_retries
                  then:
                    properties:
                      value:
                        type: integer
                        minimum: 1
                        maximum: 10
                # 当settingId为api_key时,value是32位大小写字母+数字
                - if:
                    properties:
                      $request.path.settingId:
                        const: api_key
                  then:
                    properties:
                      value:
                        type: string
                        pattern: "^[A-Za-z0-9]{32}$"

关键说明

  • OpenAPI 3.1+正式支持$request变量,可直接访问请求上下文(路径参数、查询参数、请求头等),这是实现路径参数关联校验的核心。
  • 若使用OpenAPI 3.0,部分主流工具(如OpenAPI Generator、Postman)支持类似的扩展表达式,或者可通过自定义扩展字段实现,但3.1是标准兼容方案。
  • 该方案既保持了请求体的极简结构(仅value字段),又能针对不同settingId实现精准的类型、范围或正则校验。

内容的提问来源于stack exchange,提问作者Robin Mahéo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 20:56:12