API网关-主体映射模板-可选主体参数 [英] API Gateway - Body Mapping Template - optional body parameters

查看:65
本文介绍了API网关-主体映射模板-可选主体参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个POST API网关方法,我将向其中发送以下application/json主体,以将参数从其传递到该方法所连接的Lambda:

I have a POST API Gateway method to which I am sending the following application/json body in order to pass parameters from it to a Lambda that the method is connected to:

{ 
    "otherClientId": "12345",
    "message": "Text",
    "seconds": 0,
    "hours": 0
}

我正在使用以下映射模板:

I am using the following mapping template:

#set($inputRoot = $input.path('$'))
{
  "authorizedUser": "$context.authorizer.principalId",
  "otherClientId": "$inputRoot.otherClientId",
  "message": "$inputRoot.message",
  "amount": $inputRoot.amount,
  "duration": $inputRoot.duration
}

我遇到的问题是,尝试发送没有数量或持续时间的请求时收到错误字符串"错误.由于某些原因,这些参数似乎不是可选的(但我需要将它们设为!).我能够错过其他参数,例如message,但是不能错过两个数字参数.

The problem I am experiencing is that I receive a "Bad String" error when attempting to send the request without amount or duration. For some reason these parameters do not seem to be optional (but I need them to be!). I am able to miss out other parameters, like message for instance, but not the two number parameters.

是否有人经历过这种情况,或者有人可以指出我很可能会失踪的明显现象?AWS文档对此主题很少.

Has anybody else experienced this or can somebody point out the obvious that I am probably missing? The AWS documentation is a little sparse on the subject.

推荐答案

可能是因为没有传递这些参数,您的json请求看起来像这样:

Probably, this is happening because without passing those params, your json request looks like:

#set($inputRoot = $input.path('$'))
{
  "authorizedUser": "$context.authorizer.principalId",
  "otherClientId": "$inputRoot.otherClientId",
  "message": "$inputRoot.message",
  "amount": ,
  "duration": 
}

最简单的解决方法是用引号将 $ inputRoot.amount $ inputRoot.duration 包裹起来:

The simplest way to fix is to wrap $inputRoot.amount and $inputRoot.duration with quotes:

#set($inputRoot = $input.path('$'))
{
   "authorizedUser": "$context.authorizer.principalId",
   "otherClientId": "$inputRoot.otherClientId",
   "message": "$inputRoot.message",
   "amount": "$inputRoot.amount",
   "duration": "$inputRoot.duration"
}

或者,您可以使用if条件连接请求,例如:

Alternatively, you can concatenate request using if condition for example:

#set($hasLimit = $input.params('limit') != "")
#set($hasOffset = $input.params('offset') != "")
#set($hasPeriod = $input.params('period') != "")
#set($hasType = $input.params('type') != "")
{
    "environment": "$input.params('environment')"
    #if($hasLimit),"limit": $input.params('limit')#end
    #if($hasOffset),"offset": $input.params('offset')#end
    #if($hasPeriod),"period": "$input.params('period')"#end
    #if($hasType),"type": "$input.params('type')"#end
}

这篇关于API网关-主体映射模板-可选主体参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆