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

API Gateway v2 HTTP转SQS:如何为可选请求头设置默认值?

给API Gateway v2集成SQS的可选请求头设置默认值

当你在API Gateway v2的HTTP到SQS集成中显式指定请求头映射时,若请求头为可选,直接引用${request.header.xxx}会在请求头缺失时触发"Bad Request"错误。可以通过VTL(Velocity Template Language)模板为可选请求头设置默认值,具体实现方式如下:

方法1:使用$util.defaultIfNull函数(推荐)

这是最简洁的写法,直接指定当请求头不存在时返回的默认值:

{
  "UserAgent": {
    "DataType": "String",
    "StringValue": "${request.header.user-agent}"
  },
  "anotherheader": {
    "DataType": "String",
    "StringValue": "$util.defaultIfNull($input.params('header.anotherheader'), 'default-value')"
  }
}
  • $input.params('header.anotherheader')用于获取请求头的值,若不存在则返回null
  • $util.defaultIfNull会在第一个参数为null时,返回第二个参数指定的默认值(比如'default-value',也可以设为空字符串'')

方法2:使用#if条件判断

如果需要更复杂的逻辑,可以用VTL的条件语句:

{
  "UserAgent": {
    "DataType": "String",
    "StringValue": "${request.header.user-agent}"
  },
  "anotherheader": {
    "DataType": "String",
    "StringValue": "#if($input.params('header.anotherheader'))${request.header.anotherheader}#else'default-value'#end"
  }
}

当请求头anotherheader存在时,使用实际值;不存在时则使用'default-value'。

配置步骤

  1. 登录API Gateway控制台,找到你的HTTP API对应的集成
  2. 进入集成请求设置,找到映射模板区域
  3. 选择对应的内容类型(如application/json),将原静态JSON替换为上述VTL模板
  4. 保存配置并重新部署API

这样配置后,即使请求中缺失anotherheader,API Gateway也会使用默认值发送到SQS,不会返回"Bad Request"错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 19:11:30