

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 在 API Gateway 中設定 Lambda 自訂整合
<a name="set-up-lambda-custom-integrations"></a>

 為了示範如何設定 Lambda 自訂或非代理整合，我們會建立 API Gateway API 來公開 `GET /greeting?greeter={name}` 方法以調用 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>

**使用 設定 Lambda 自訂整合 AWS CLI**

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)，使用 HTTP 方法 `POST` 進行整合請求。`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"
   }
   ```

   IAM 角色 `apigAwsProxyRole` 的政策必須允許 `apigateway` 服務叫用 Lambda 函數。您可以呼叫 [add-permission](https://docs.aws.amazon.com/cli/latest/reference/lambda/add-permission.html) 命令來新增資源型許可，而不提供 `credentials` 的 IAM 角色。這是 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'
   ```