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

API Gateway映射模板问题:路径参数与请求体解析异常

API Gateway映射模板配置修复方案

问题现象

PUT请求端点路径为/progress/{clientNumber},请求体包含顶层progress对象,但映射后传递给Lambda的请求体存在两个问题:

  • clientNumber字段为空
  • progress字段被转为字符串格式的键值对(如"{progress={client={name=client, site={name=site}}}}"),而非原始JSON对象

问题根源

  1. 模板生成方式错误:通过JSON.stringify(requestTemplates)将模板对象转为字符串,导致Velocity模板语法(如$input.params)被转义,API Gateway无法正确解析变量
  2. 请求体取值逻辑错误:使用$input.json('progress')的写法不符合Velocity路径语法,且模板构造方式导致返回结果被序列化为字符串

修复方案

修改apiUtils.createLambdaIntegrationOptions函数,直接构造符合Velocity语法的映射模板字符串,而非通过JSON序列化生成:

export function createLambdaIntegrationOptions(
    pathParams: string[],
    integrationResponses: IntegrationResponse[], 
    bodyParam?: string): LambdaIntegrationOptions {
  const requestParams: {[key: string]: string} = {};

  // 生成路径参数的模板片段
  const pathParamSegments = pathParams.map(item => {
    requestParams[`integration.request.path.${item}`] = `method.request.path.${item}`;
    return `"${item}": "$input.params('${item}')"`;
  }).join(',\n  ');

  // 生成请求体参数的模板片段
  let bodySegment = '';
  if (bodyParam) {
    bodySegment = pathParamSegments ? ',\n  ' : '';
    // 使用$.bodyParam的JSONPath语法提取请求体中的对象
    bodySegment += `"${bodyParam}": $input.json('$.${bodyParam}')`;
  }

  // 拼接完整的JSON映射模板
  const requestTemplate = `{
  ${pathParamSegments}${bodySegment}
}`;

  const opts = {
    proxy: false,
    requestParameters: requestParams,
    requestTemplates: {"application/json": requestTemplate},
    integrationResponses: integrationResponses
  };

  return opts;
}

关键修改点

  1. 直接构造模板字符串:避免JSON序列化对Velocity语法的转义,确保API Gateway能正确执行模板变量解析
  2. 正确提取路径参数:通过$input.params('clientNumber')直接获取路径参数,保证字段值不为空
  3. 正确提取请求体对象:使用$input.json('$.progress')的JSONPath语法,直接从请求体中提取progress对象,返回原生JSON结构而非字符串

修复后效果

转换后的请求体将符合预期:

{
  "clientNumber": "12345",
  "progress": {
    "client": {
      "name": "client",
      "site": {
        "name": "site"
      }
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 13:29:55