LoginSignup
2
1

More than 3 years have passed since last update.

マッピングテンプレートでGETの可変パラメータに対応する

Posted at

LambdaとAPI GatewayでAPIを作成していて、GETのパラメータがあったり無かったりする場合にマッピングテンプレートでどう対応するかのメモ。
探すのにだいぶ時間かかったので・・

以下のようなGETメソッドに対応したいのです。
https://www.example.com/api/hoge?user_id=abc
https://www.example.com/api/hoge?user_id=abc&limit=100

通常のマッピングテンプレートの指定方法

{
    "user_id" : "$input.params('user_id')",
    "limit" : "$input.params('limit')"
}

ですが、上記の書き方でlimitの引数を入れない状態でAPIをコールすると、以下のようなエラーが返却されます。

"errorMessage": "Unable to marshal response: ClientError('An error occurred (ValidationException) when calling the Query operation: The provided starting key is invalid: One or more parameter values were invalid: An AttributeValue may not contain an empty string') is not JSON serializable", "errorType"

解決方法

#set($limit = $input.params('limit'))
{
    #if($limit && $limit.length() != 0)
        "limit": "$input.params('limit')",
    #end
    "user_id" : "$input.params('user_id')"
}

参考

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1