LoginSignup
5
5

More than 5 years have passed since last update.

APIGateway から Lambda を非同期で呼び出す方法

Last updated at Posted at 2018-10-02

APIGateway から Lambda を呼び出す場合に、統合タイプで Lambda 関数 を選択すると常に同期呼び出しになってしまう。
スクリーンショット 2018-10-02 15.51.51.png

非同期で Lambda を呼び出すには統合タイプで AWS サービス を選択する必要がある。
スクリーンショット 2018-10-02 15.54.20.png

HTTPヘッダーで X-Amz-Invocation-Type: 'Event' を設定する。
スクリーンショット 2018-10-02 16.03.42.png

application/x-www-form-urlencoded のマッピングテンプレートを設定する。
スクリーンショット 2018-10-02 16.06.28.png

#set($rawAPIData = $input.path('$'))
## escape any quotes
#set($rawAPIData = $rawAPIData.replace('"', '\"'))

## first we get the number of "&" in the string, this tells us if there is more than one key value pair
#set($countAmpersands = $rawAPIData.length() - $rawAPIData.replace("&", "").length())

## if there are no "&" at all then we have only one key value pair.
## we append an ampersand to the string so that we can tokenise it the same way as multiple kv pairs.
## the "empty" kv pair to the right of the ampersand will be ignored anyway.
#if ($countAmpersands == 0)
 #set($rawPostData = $rawAPIData + "&")
#end

## now we tokenise using the ampersand(s)
#set($tokenisedAmpersand = $rawAPIData.split("&"))

## we set up a variable to hold the valid key value pairs
#set($tokenisedEquals = [])

## now we set up a loop to find the valid key value pairs, which must contain only one "="
#foreach( $kvPair in $tokenisedAmpersand )
 #set($countEquals = $kvPair.length() - $kvPair.replace("=", "").length())
 #if ($countEquals == 1)
  #set($kvTokenised = $kvPair.split("="))
  #if ($kvTokenised[0].length() > 0)
   ## we found a valid key value pair. add it to the list.
   #set($devNull = $tokenisedEquals.add($kvPair))
  #end
 #end
#end

{
    "headers" : {
#foreach( $key in $input.params().header.keySet() )
       "$key" : "$input.params().header.get($key)"#if( $foreach.hasNext ),#end
#end
    },
    "querystring" : {
#foreach( $kvPair in $tokenisedEquals )
  ## finally we output the JSON for this pair and append a comma if this isn't the last pair
  #set($kvTokenised = $kvPair.split("="))
  #if($kvTokenised.size() == 2 && $kvTokenised[1].length() > 0)
    #set($kvValue = $kvTokenised[1])
  #else
    #set($kvValue = "")
  #end
  #if( $foreach.hasNext )
    #set($itemDelimiter = ",")
  #else
    #set($itemDelimiter = "")
  #end
 "$kvTokenised[0]" : "$kvValue"$itemDelimiter
#end
    },
    "stage" : "$context.stage",
    "sourceIp" : "$context.identity.sourceIp",
    "userAgent" : "$context.identity.userAgent"
}

これでデプロイすれば、非同期で API Gateway から Lambda 関数を呼び出すことができるはずです。

5
5
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
5
5