

# 在 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
```

------

在 `greeter` 参数值为非空字符串时，该函数使用消息 `"Hello, {name}!"` 进行响应。如果 `greeter` 值是空字符串，则返回消息 `"Hello, World!"`。如果传入请求中未设置 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 函数的集成。在提供 `greeter` 参数时，函数使用消息 `"Hello, {name}!"` 响应请求，在未设置查询字符串参数时使用 `"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
   ```

   此处提供的映射模板转换为 JSON 负载 `greeter` 属性的 `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"
   }
   ```

   `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 ""
   ```

   将 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'
   ```