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

API Gateway集成DDB处理x-www-form-urlencoded请求失败排查

解决API Gateway处理x-www-form-urlencoded数据到DynamoDB的问题

核心结论

纯VTL模板完全可以解决问题,无需引入Lambda。你的问题源于两个关键点:

  • VTL模板生成的JSON格式无效(日志语句混入输出内容)
  • API Gateway的日志配置未正确开启,导致$util.log()的内容无法查看

修正x-www-form-urlencoded映射模板

API Gateway会自动解析x-www-form-urlencoded格式的请求参数到$input.params()集合中,无需手动拆分body。直接使用以下模板构造符合DynamoDB PutItem要求的请求:

{
  "TableName": "${aws_dynamodb_table.generic_data.name}",
  "Item": {
    "lon": {
      "N": "$util.urlDecode($input.params('lon'))"
    },
    "lat": {
      "N": "$util.urlDecode($input.params('lat'))"
    },
    "timestamp": {
      "S": "$util.urlDecode($input.params('timestamp'))"
    }
  }
}

模板说明

  • $input.params('lon')直接获取表单中的lon参数值
  • $util.urlDecode()处理参数的URL编码(比如空格、特殊字符)
  • 严格遵循DynamoDB的数据类型格式:N类型对应字符串形式的数字,S类型对应字符串

启用VTL日志输出到CloudWatch

要让$util.log()的内容显示在CloudWatch中,需要完成以下配置:

1. 配置API Gateway日志级别

在Terraform中为API Gateway Stage添加日志配置,设置日志级别为INFO(或更详细的DEBUG):

resource "aws_api_gateway_stage" "generic_stage" {
  rest_api_id = aws_api_gateway_rest_api.generic_api.id
  deployment_id = aws_api_gateway_deployment.generic_deployment.id
  stage_name = "prod"

  access_log_settings {
    destination_arn = aws_cloudwatch_log_group.api_gw_logs.arn
    format = jsonencode({
      requestId = "$context.requestId"
      ip = "$context.identity.sourceIp"
      caller = "$context.identity.caller"
      user = "$context.identity.user"
      requestTime = "$context.requestTime"
      httpMethod = "$context.httpMethod"
      resourcePath = "$context.resourcePath"
      status = "$context.status"
      protocol = "$context.protocol"
      responseLength = "$context.responseLength"
      integrationLatency = "$context.integrationLatency"
      logData = "$context.logData"
    })
  }

  depends_on = [aws_api_gateway_deployment.generic_deployment]
}

# 对应的CloudWatch Log Group
resource "aws_cloudwatch_log_group" "api_gw_logs" {
  name = "/aws/api-gateway/${aws_api_gateway_rest_api.generic_api.name}"
  retention_in_days = 30
}

2. 确保IAM角色权限

为API Gateway的执行角色添加CloudWatch Logs的写入权限:

resource "aws_iam_role_policy" "api_gw_log_policy" {
  name = "api-gw-cloudwatch-logs"
  role = aws_iam_role.api_gw_to_ddb.id

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Effect = "Allow"
        Action = [
          "logs:CreateLogStream",
          "logs:PutLogEvents"
        ]
        Resource = aws_cloudwatch_log_group.api_gw_logs.arn
      }
    ]
  })
}

3. 在VTL中正确使用日志

注意:$util.log()语句不能混入JSON输出内容中,必须放在模板的开头或结尾(不影响JSON结构的位置),例如:

$util.log("Processing x-www-form-urlencoded request, params: lon=$input.params('lon'), lat=$input.params('lat'), timestamp=$input.params('timestamp')")
{
  "TableName": "${aws_dynamodb_table.generic_data.name}",
  "Item": {
    "lon": {
      "N": "$util.urlDecode($input.params('lon'))"
    },
    "lat": {
      "N": "$util.urlDecode($input.params('lat'))"
    },
    "timestamp": {
      "S": "$util.urlDecode($input.params('timestamp'))"
    }
  }
}

验证步骤

  1. 重新部署API Gateway(Terraform apply后需触发部署)
  2. 使用PhoneTrack发送请求,或用curl模拟x-www-form-urlencoded请求:
curl -X POST https://<your-api-id>.execute-api.<region>.amazonaws.com/prod/<resource-path> \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "lon=123.45&lat=67.89&timestamp=2024-05-20T12:00:00Z"
  1. 查看CloudWatch Log Group中的日志,确认参数解析和模板执行是否正常

内容的提问来源于stack exchange,提问作者Thom-AwS

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 17:55:56