

# API Gateway에서 Lambda 사용자 지정 통합 설정
<a name="set-up-lambda-custom-integrations"></a>

 Lambda 사용자 지정, 비프록시, 통합을 설정하는 방법을 보여주기 위해 API Gateway API를 만들어 Lambda 함수를 호출할 `GET /greeting?greeter={name}` 메서드를 공개합니다. 다음 예시 Lambda 함수 중 하나를 API에 사용하십시오.

다음 예시 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) 명령을 사용하면 `HelloWorld`라는 Lambda 함수와 `GET /greeting?greeter={name}` 메서드의 통합을 설정할 수 있습니다. 이 함수는 `"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'
   ```