

# 使用 AWS CLI 为 API Gateway 设置 Lambda 代理集成
<a name="set-up-lambda-proxy-integration-using-cli"></a>

在此部分中，我们将介绍如何使用 AWS CLI 设置 API 与 Lambda 代理集成。有关使用 API Gateway 控制台配置与 Lambda 代理集成的代理资源的详细说明，请参阅 [教程：利用 Lambda 代理集成创建 REST API](api-gateway-create-api-as-simple-proxy-for-lambda.md)。

例如，我们使用以下示例 Lambda 函数作为 API 的后端：

```
export const handler = async(event, context) => {
    console.log('Received event:', JSON.stringify(event, null, 2));
    var res ={
        "statusCode": 200,
        "headers": {
            "Content-Type": "*/*"
        }
    };
    var greeter = 'World';
    if (event.greeter && event.greeter!=="") {
        greeter =  event.greeter;
    } else if (event.body && event.body !== "") {
        var body = JSON.parse(event.body);
        if (body.greeter && body.greeter !== "") {
            greeter = body.greeter;
        }
    } else if (event.queryStringParameters && event.queryStringParameters.greeter && event.queryStringParameters.greeter !== "") {
        greeter = event.queryStringParameters.greeter;
    } else if (event.multiValueHeaders && event.multiValueHeaders.greeter && event.multiValueHeaders.greeter != "") {
        greeter = event.multiValueHeaders.greeter.join(" and ");
    } else if (event.headers && event.headers.greeter && event.headers.greeter != "") {
        greeter = event.headers.greeter;
    } 
    res.body = "Hello, " + greeter + "!";
    return res
};
```

将这一点与[在 API Gateway 中设置 Lambda 自定义集成](set-up-lambda-custom-integrations.md)中的 Lambda 自定义集成设置对比，对此 Lambda 函数的输入可能出现在请求参数和正文中。您可以有更多的自主度来允许客户端传递相同的输入数据。在这里，客户端可以将欢迎者的姓名作为查询字符串参数、标题或正文属性传递。该函数还支持 Lambda 自定义集成。API 设置更简单。您完全无需配置方法响应或集成响应。

**使用 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": "HelloWorldProxy (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 {proxy+}
   ```

   输出将与以下内容类似：

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

   在下一步中，您可以使用 `{proxy+}` 资源的 `id` 值（`2jf6xt`），在 `/{proxy+}` 资源上创建方法。

1. 使用以下 [put-method](https://docs.aws.amazon.com/cli/latest/reference/apigateway/put-method.html) 创建 `ANY /{proxy+}` 的 `ANY` 方法请求：

   ```
   aws apigateway put-method --rest-api-id te6si5ach7 \
          --resource-id 2jf6xt \
          --http-method ANY \
          --authorization-type "NONE"
   ```

   输出将与以下内容类似：

   ```
   {
       "apiKeyRequired": false, 
       "httpMethod": "ANY", 
       "authorizationType": "NONE"
   }
   ```

   此 API 方法允许客户端从后端的 Lambda 函数接收或发送问候语。

1. 使用以下 [put-integration](https://docs.aws.amazon.com/cli/latest/reference/apigateway/put-integration.html) 命令，设置 `ANY /{proxy+}` 方法与名为 `HelloWorld` 的 Lambda 函数的集成。在提供 `greeter` 参数时，此函数使用消息 `"Hello, {name}!"` 响应请求，在未设置查询字符串参数时使用 `"Hello, World!"` 响应。

   ```
   aws apigateway put-integration \
         --rest-api-id te6si5ach7 \
         --resource-id 2jf6xt \
         --http-method ANY \
         --type AWS_PROXY \
         --integration-http-method POST \
         --uri arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:123456789012:function:HelloWorld/invocations \
         --credentials arn:aws:iam::123456789012:role/apigAwsProxyRole
   ```
**重要**  
对于 Lambda 集成，根据[函数调用的 Lambda 服务操作规范](https://docs.aws.amazon.com/lambda/latest/api/API_Invoke.html)，您必须为集成请求使用 HTTP 方法 `POST`。`apigAwsProxyRole` 的 IAM 角色必须具有策略，允许 `apigateway` 服务调用 Lambda 函数。有关 IAM 权限的更多信息，请参阅[用于调用 API 的 API Gateway 权限模型](permissions.md#api-gateway-control-access-iam-permissions-model-for-calling-api)。

   输出将与以下内容类似：

   ```
   {
       "passthroughBehavior": "WHEN_NO_MATCH", 
       "cacheKeyParameters": [], 
       "uri": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:1234567890:function:HelloWorld/invocations", 
       "httpMethod": "POST", 
       "cacheNamespace": "vvom7n", 
       "credentials": "arn:aws:iam::1234567890:role/apigAwsProxyRole", 
       "type": "AWS_PROXY"
   }
   ```

   您不用为 `credentials` 提供 IAM 角色，而是可以使用 [add-permission](https://docs.aws.amazon.com/cli/latest/reference/lambda/add-permission.html) 命令添加基于资源的权限。这是 API Gateway 控制台的功能。

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。

   使用查询字符串参数 `?greeter=jane` 调用 API：

   ```
   curl -X GET 'https://te6si5ach7.execute-api.us-west-2.amazonaws.com/test/greeting?greeter=jane'
   ```

   使用 `greeter:jane` 的标头参数调用 API：

   ```
   curl -X GET https://te6si5ach7.execute-api.us-west-2.amazonaws.com/test/hi \
     -H 'content-type: application/json' \
     -H 'greeter: jane'
   ```

   使用 `{"greeter":"jane"}` 的正文调用 API：

   ```
   curl -X POST https://te6si5ach7.execute-api.us-west-2.amazonaws.com/test/hi \
     -H 'content-type: application/json' \
     -d '{ "greeter": "jane" }'
   ```

   在所有情况下，输出为具有以下响应正文的 200 响应：

   ```
   Hello, jane!
   ```