

# API Gateway で Lambda カスタム統合を設定する
<a name="set-up-lambda-custom-integrations"></a>

 カスタムの Lambda 統合または非プロキシ統合をセットアップする方法を表示するには、`GET /greeting?greeter={name}` メソッドを公開する API Gateway API を作成して、Lambda 関数を呼び出します。API には、次の Lambda 関数の例のいずれかを使用します。

次の Lambda 関数の例のいずれかを使用します。

------
#### [ Node.js ]

```
'use strict';
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];            
var times = ['morning', 'afternoon', 'evening', 'night', 'day'];

export const handler = async(event) => {
  console.log(event);
  // Parse the input for the name, city, time and day property values
  let name = event.name === null || event.name === undefined || event.name === "" ? 'you' : event.name;
  let city = event.city === undefined ? 'World' : event.city;
  let time = times.indexOf(event.time)<0 ? 'day' : event.time;
  let day = days.indexOf(event.day)<0 ? null : event.day;

  // Generate a greeting
  let greeting = 'Good ' + time + ', ' + name + ' of ' + city + '. ';
  if (day) greeting += 'Happy ' + day + '!';
  
  // Log the greeting to CloudWatch
  console.log('Hello: ', greeting);
  
  // Return a greeting to the caller
  return greeting;
};
```

------
#### [ Python ]

```
import json


def lambda_handler(event, context):
    print(event)
    res = {
        "statusCode": 200,
        "headers": {
            "Content-Type": "*/*"
        }
    }

    if event['greeter'] == "":
        res['body'] = "Hello, World"
    elif (event['greeter']):
        res['body'] = "Hello, " + event['greeter'] + "!"
    else:
        raise Exception('Missing the required greeter parameter.')

    return res
```

------

この関数は、`"Hello, {name}!"` パラメータの値が空白でない文字列の場合は、`greeter` のメッセージで応答します。`"Hello, World!"` の値が空の文字列の場合は、`greeter` のメッセージを返します。着信リクエストで greeter パラメータが設定されていない場合、この関数は `"Missing the required greeter parameter."` のエラーメッセージを返します。関数名を `HelloWorld` とします。

これは、Lambda コンソールで、または AWS CLI を使用して作成できます。このセクションでは、次の ARN を使用してこの関数を参照します。

```
arn:aws:lambda:us-east-1:123456789012:function:HelloWorld
```

バックエンドに Lambda 関数を設定すると、API のセットアップに進みます。<a name="set-up-lambda-custom-integration-using-cli"></a>

**AWS CLI を使用して Lambda カスタム統合をセットアップするには**

1. 次の [create-rest-api](https://docs.aws.amazon.com/cli/latest/reference/apigateway/create-rest-api.html) コマンドを使用して、API を作成します。

   ```
   aws apigateway create-rest-api --name 'HelloWorld (AWS CLI)'
   ```

   出力は次のようになります。

   ```
   {
       "name": "HelloWorld (AWS CLI)", 
       "id": "te6si5ach7",
       "rootResourceId" : "krznpq9xpg",
       "createdDate": 1508461860
   }
   ```

   この例全体で、API `id` (`te6si5ach7`) と `rootResourceId` (`krznpq9xpg`) を使用します。

1. 次の [create-resource](https://docs.aws.amazon.com/cli/latest/reference/apigateway/create-resource.html) コマンドを使用して、`/greeting` の API Gateway [リソース](https://docs.aws.amazon.com/apigateway/latest/api/API_Resource.html) を作成します。

   ```
   aws apigateway create-resource \
         --rest-api-id te6si5ach7 \
         --parent-id krznpq9xpg \
         --path-part greeting
   ```

   出力は次のようになります。

   ```
   {
       "path": "/greeting", 
       "pathPart": "greeting", 
       "id": "2jf6xt", 
       "parentId": "krznpq9xpg"
   }
   ```

   次のステップでは、`greeting` リソースの `id` 値 (`2jf6xt`) を使用して `/greeting` リソースにメソッドを作成します。

1. 次の [put-method](https://docs.aws.amazon.com/cli/latest/reference/apigateway/put-method.html) コマンドを使用して、`GET /greeting?greeter={name}` の API メソッドリクエストを作成します。

   ```
   aws apigateway put-method --rest-api-id te6si5ach7 \
          --resource-id 2jf6xt \
          --http-method GET \
          --authorization-type "NONE" \
          --request-parameters method.request.querystring.greeter=false
   ```

   出力は次のようになります。

   ```
   {
       "apiKeyRequired": false, 
       "httpMethod": "GET", 
       "authorizationType": "NONE", 
       "requestParameters": {
           "method.request.querystring.greeter": false
       }
   }
   ```

   この API メソッドでは、クライアントはバックエンドの Lambda 関数からお知らせを受信できます。バックエンドは匿名の発信者または匿名でない発信者のいずれかを処理する必要があるため、この `greeter` パラメータはオプションです。

1. 次の [put-method-response](https://docs.aws.amazon.com/cli/latest/reference/apigateway/put-method-response.html) コマンドを使用して、`GET /greeting?greeter={name}` メソッドリクエストに対する `200 OK` レスポンスを設定します。

   ```
   aws apigateway put-method-response \
           --rest-api-id te6si5ach7 \ 
           --resource-id 2jf6xt \
           --http-method GET \
           --status-code 200
   ```

   

1. 次の [put-integration](https://docs.aws.amazon.com/cli/latest/reference/apigateway/put-integration.html) コマンドを使用して、`GET /greeting?greeter={name}` メソッドと `HelloWorld` という名前の Lambda 関数との統合を設定します。この関数は、`"Hello, {name}!"` パラメータが提供されている場合は `greeter`、クエリ文字列パラメータが設定されていない場合は `"Hello, World!"` のメッセージでリクエストに応答します。

   ```
   aws apigateway put-integration \
           --rest-api-id te6si5ach7 \
           --resource-id 2jf6xt \
           --http-method GET \
           --type AWS \
           --integration-http-method POST \
           --uri arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:123456789012:function:HelloWorld/invocations \
           --request-templates '{"application/json":"{\"greeter\":\"$input.params('greeter')\"}"}' \
           --credentials arn:aws:iam::123456789012:role/apigAwsProxyRole
   ```

   ここで指定されたマッピングテンプレートは、`greeter` クエリ文字列パラメータを JSON ペイロードの `greeter` プロパティに変換します。Lambda 関数への入力を本文で表現する必要があるため、これが必要になります。
**重要**  
Lambda 統合では、[関数呼び出しの Lambda サービスアクションの仕様](https://docs.aws.amazon.com/lambda/latest/api/API_Invoke.html)に従って、統合リクエストに `POST` の HTTP メソッドを使用する必要があります。`uri` パラメータは、関数呼び出しアクションの ARN です。  
出力は次のようになります。

   ```
   {
       "passthroughBehavior": "WHEN_NO_MATCH", 
       "cacheKeyParameters": [], 
       "uri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:123456789012:function:HelloWorld/invocations", 
       "httpMethod": "POST", 
       "requestTemplates": {
           "application/json": "{\"greeter\":\"$input.params('greeter')\"}"
       }, 
       "cacheNamespace": "krznpq9xpg", 
       "credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole", 
       "type": "AWS"
   }
   ```

   `apigAwsProxyRole` の IAM ロールは、`apigateway` サービスが Lambda 関数を呼び出せるようにするポリシーが必要です。`credentials` の IAM ロールを指定する代わりに、[add-permission](https://docs.aws.amazon.com/cli/latest/reference/lambda/add-permission.html) コマンドを呼び出して、リソースベースのアクセス許可を追加することができます。これは、API Gateway コンソールがこれらのアクセス許可を追加する方法です。

1. 次の [put-integration-response](https://docs.aws.amazon.com/cli/latest/reference/apigateway/put-integration-response.html) コマンドを使用して、Lambda 関数の出力を `200 OK` メソッドレスポンスとしてクライアントに渡すための統合レスポンスを設定します。

   ```
    aws apigateway put-integration-response \
           --rest-api-id te6si5ach7 \
           --resource-id 2jf6xt \
           --http-method GET \
           --status-code 200 \
           --selection-pattern ""
   ```

   選択パターンを空の文字列に設定すると、`200 OK` レスポンスがデフォルトになります。

   出力は次のようになります。

   ```
    {
       "selectionPattern": "", 
       "statusCode": "200"
   }
   ```

1. 次の [create-deployment](https://docs.aws.amazon.com/cli/latest/reference/apigateway/create-deployment.html) コマンドを使用して、API を `test` ステージにデプロイします。

   ```
   aws apigateway create-deployment \
           --rest-api-id te6si5ach7 \
           --stage-name test
   ```

1.  ターミナルで次の cURL コマンドを使用して API をテストします。

   ```
   curl -X GET 'https://te6si5ach7.execute-api.us-west-2.amazonaws.com/test/greeting?greeter=me' \
     -H 'authorization: AWS4-HMAC-SHA256 Credential={access_key}/20171020/us-west-2/execute-api/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=f327...5751'
   ```