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

如何在Swagger JSON文件中添加真实API密钥及必填参数值?

正确在Swagger/OpenAPI JSON中配置真实API密钥与必填参数值

一、按参数类型的规范配置方法

1. API密钥(Header/Query 位置)

API密钥通常放在请求头或查询参数中,不要用非标准的value字段(这是你解析失败的核心原因),需遵循OpenAPI规范用example字段,分版本写法如下:

OpenAPI 3.x 写法

{
  "paths": {
    "/balance": {
      "get": {
        "parameters": [
          {
            "name": "X-API-Key",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string",
              "example": "your-real-api-key-76t8g9hj"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Balance retrieved successfully"
          }
        }
      }
    }
  }
}

Swagger 2.0(OpenAPI 2.0)写法

{
  "swagger": "2.0",
  "paths": {
    "/balance": {
      "get": {
        "parameters": [
          {
            "name": "X-API-Key",
            "in": "header",
            "required": true,
            "type": "string",
            "example": "your-real-api-key-76t8g9hj"
          }
        ],
        "responses": {
          "200": {
            "description": "Balance retrieved successfully"
          }
        }
      }
    }
  }
}

2. 路径/查询必填参数

对于路径参数(如/user/{userId})或查询参数,同样用example字段定义真实值:

{
  "parameters": [
    {
      "name": "userId",
      "in": "path",
      "required": true,
      "schema": {
        "type": "string",
        "example": "user_1001_real_id"
      }
    },
    {
      "name": "accountType",
      "in": "query",
      "required": true,
      "schema": {
        "type": "string",
        "example": "savings"
      }
    }
  ]
}

3. 请求体中的必填参数

如果是POST/PUT接口的请求体,在schema.properties下为每个必填字段添加example:

{
  "requestBody": {
    "required": true,
    "content": {
      "application/json": {
        "schema": {
          "type": "object",
          "required": ["amount", "targetAccount"],
          "properties": {
            "amount": {
              "type": "number",
              "example": 500.75
            },
            "targetAccount": {
              "type": "string",
              "example": "acc_8765_real"
            }
          }
        }
      }
    }
  }
}

二、解析异常的排查要点

  1. 禁用非标准value字段:OpenAPI规范中没有value作为参数值定义的标准字段,解析器会直接忽略或抛出异常,必须替换为example。
  2. 匹配OpenAPI版本:如果你的解析器只支持特定版本(比如仅Swagger 2.0),混用3.x的写法会导致解析失败,严格对应版本格式。
  3. 校验JSON语法:确保文件没有语法错误(如逗号遗漏、引号不闭合),用JSON校验工具检查格式合法性。
  4. 检查解析器配置:部分API解析工具默认会忽略example字段,需开启“启用示例值”或类似配置,才能读取到真实参数值。

三、重要提醒

  • 包含真实API密钥的Swagger文件属于敏感数据,客户上传和存储时必须加密,避免泄露。
  • 如果需要动态注入密钥(而非硬编码),可以用占位符(如{{API_KEY}}),再让你的产品支持环境变量替换;若必须在文件中包含真实值,严格遵循上述规范写法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 15:01:21