

# API Gateway에서 REST API의 데이터 변환
<a name="rest-api-data-transformations"></a>

**참고**  
이 섹션에서는 비프록시 통합에 사용하는 기능에 대해 설명합니다. 그러나 가능하면 REST API에 프록시 통합을 사용하는 것이 좋습니다. 프록시 통합에는 간소화된 통합 설정이 있으며 기존 설정을 손상하지 않고 백엔드와 함께 진화할 수 있습니다. 자세한 내용은 [API Gateway API 통합 유형 선택](api-gateway-api-integration-types.md) 섹션을 참조하세요.

비프록시 통합을 사용하는 경우 API Gateway의 2가지 기능을 사용하여 메서드 요청과 통합 응답을 변환할 수 있습니다. 통합 요청 페이로드와 다른 페이로드 형식을 사용하는 경우 메서드 요청을 변환할 수 있습니다. 메서드 응답에서 반환해야 하는 형식과 다른 페이로드 형식을 반환하는 경우 통합 응답을 변환할 수 있습니다. 요청 수명 주기에 대한 자세한 내용은 [REST API에 대한 리소스 예제](rest-api-develop.md#rest-api-develop-example) 섹션을 참조하시기 바랍니다.

다음 예제는 `"x-version:beta"` 헤더의 경우 `x-version` 헤더 파라미터가 `app-version` 헤더 파라미터로 변환되는 데이터 변환을 보여줍니다. `x-version`에서 `app-version`으로의 데이터 변환은 통합 요청에서 발생합니다. 이렇게 하면 통합 엔드포인트가 변환된 헤더 파라미터 값을 수신합니다. 통합 엔드포인트가 상태 코드를 반환하면 상태 코드가 메서드 응답 전에 `200`에서 `204`로 변환됩니다.

![\[API Gateway 데이터 변환 다이어그램\]](http://docs.aws.amazon.com/ko_kr/apigateway/latest/developerguide/images/develop-non-proxy.png)


데이터 변환을 만들기 위해 다음 기능을 사용할 수 있습니다.

**파라미터 매핑**  
파라미터 매핑에서 통합 요청 URL 경로 파라미터, URL 쿼리 문자열 파라미터 또는 HTTP 헤더 값을 수정할 수 있지만 통합 요청 페이로드를 수정할 수 없습니다. 또한 HTTP 응답 헤더 값을 수정할 수 있습니다. 파라미터 매핑을 사용하여 교차 오리진 리소스 공유(CORS)에 대한 정적 헤더 값을 만듭니다.  
프록시 및 비 프록시 통합에 대한 통합 요청에서 파라미터 매핑을 사용할 수 있지만 통합 응답에 파라미터 매핑을 사용하려면 비 프록시 통합이 필요합니다. 파라미터 매핑에는 [Velocity Template Language(VTL)](https://velocity.apache.org/engine/devel/vtl-reference.html)의 스크립팅이 필요하지 않습니다. 자세한 내용은 [API Gateway의 REST API 대한 파라미터 매핑](rest-api-parameter-mapping.md) 섹션을 참조하세요.

**템플릿 변환 매핑**  
매핑 템플릿 변환에서 매핑 템플릿을 사용하여 URL 경로 파라미터, URL 쿼리 문자열 파라미터, HTTP 헤더, 통합 요청 또는 통합 응답 본문을 매핑합니다. *매핑 템플릿*이란 [Velocity Template Language(VTL)](https://velocity.apache.org/engine/devel/vtl-reference.html)로 표현된 스크립트로, [JSONPath 표현식](https://goessner.net/articles/JsonPath/)을 사용하여 `Content-type` 헤더 기반 페이로드에 적용됩니다.  
매핑 템플릿을 사용하여 다음을 수행할 수 있습니다.  
+ Amazon DynamoDB 또는 Lambda 함수 또는 HTTP 엔드포인트와 같은 AWS 서비스와의 통합을 사용하여 전송할 데이터를 선택합니다. 자세한 내용은 [자습서: AWS 서비스에 대한 통합의 통합 요청 및 응답 수정](set-up-data-transformations-in-api-gateway.md) 섹션을 참조하세요.
+ API의 통합 요청 및 통합 응답 파라미터를 조건부로 재정의하고, 새 헤더 값을 만들고, 상태 코드를 재정의합니다. 자세한 내용은 [API Gateway에서 REST API에 대한 API 요청, 응답 파라미터, 상태 코드 재정의](apigateway-override-request-response-parameters.md) 섹션을 참조하세요.
또한 통합 요청 본문에 일치하는 매핑 템플릿이 없는 `Content-type` 헤더가 있는 경우 API의 동작을 지정할 수 있습니다. 통합 패스스루 동작이라고 합니다. 자세한 내용은 [API Gateway의 REST API에 대한 매핑 템플릿이 없는 페이로드의 메서드 요청 동작](integration-passthrough-behaviors.md) 섹션을 참조하세요.

## 파라미터 매핑과 매핑 템플릿 변환 중에서 선택
<a name="rest-api-data-transformations-choose"></a>

가능하면 파라미터 매핑을 사용하여 데이터를 변환하는 것이 좋습니다. API에서 본문을 변경해야 하거나 수신 통합 요청 또는 통합 응답에 따라 조건부 재정의 및 수정을 수행해야 하고 프록시 통합을 사용할 수 없는 경우 매핑 템플릿 변환을 사용합니다.

# API Gateway의 REST API 대한 파라미터 매핑
<a name="rest-api-parameter-mapping"></a>

**참고**  
HTTP API를 사용하는 경우 [API Gateway에서 HTTP API에 대한 API 요청 및 응답 변환](http-api-parameter-mapping.md) 섹션을 참조하시기 바랍니다.

파라미터 매핑에서 요청 또는 응답 파라미터를 매핑합니다. 파라미터 매핑 표현식 또는 정적 값을 사용하여 파라미터를 매핑할 수 있습니다. 매핑 표현식 목록은 [API Gateway의 REST API에 대한 파라미터 매핑 소스 참조](rest-api-parameter-mapping-sources.md) 섹션을 참조하시기 바랍니다. 프록시 및 비 프록시 통합에 대한 통합 요청에서 파라미터 매핑을 사용할 수 있지만 통합 응답에 파라미터 매핑을 사용하려면 비 프록시 통합이 필요합니다.

예를 들어 메서드 요청 헤더 파라미터(`puppies`)를 통합 요청 헤더 파라미터(`DogsAge0`)에 매핑할 수 있습니다. 그런 다음 클라이언트가 API로 `puppies:true` 헤더를 보내면 통합 요청은 요청 헤더(`DogsAge0:true`)를 통합 엔드포인트로 보냅니다. 다음 다이어그램은 이 예제의 요청 수명 주기를 보여줍니다.

![\[요청에 대한 API Gateway 파라미터 매핑 예제 다이어그램\]](http://docs.aws.amazon.com/ko_kr/apigateway/latest/developerguide/images/parameter-mapping-example1.png)


API Gateway를 사용하여 이 예제를 만들려면 [예제 1: 메서드 요청 파라미터를 통합 요청 파라미터에 매핑](request-response-data-mappings.md#request-response-data-mappings-example-1) 섹션을 참조하시기 바랍니다.

 또 다른 예제로, 통합 응답 헤더 파라미터(`kittens`)를 메서드 응답 헤더 파라미터(`CatsAge0`)에 매핑할 수 있습니다. 그런 다음 통합 엔드포인트가 `kittens:false`를 반환하면 클라이언트는 `CatsAge0:false` 헤더를 수신합니다. 다음 다이어그램은 이 예제의 요청 수명 주기를 보여줍니다.

![\[응답에 대한 API Gateway 파라미터 매핑 예제 다이어그램\]](http://docs.aws.amazon.com/ko_kr/apigateway/latest/developerguide/images/parameter-mapping-example2.png)


**Topics**
+ [API Gateway의 REST API에 대한 파라미터 매핑 예제](request-response-data-mappings.md)
+ [API Gateway의 REST API에 대한 파라미터 매핑 소스 참조](rest-api-parameter-mapping-sources.md)

# API Gateway의 REST API에 대한 파라미터 매핑 예제
<a name="request-response-data-mappings"></a>

다음 예제에서는 API Gateway 콘솔, OpenAPI 및 CloudFormation 템플릿을 사용하여 파라미터 매핑 표현식을 만드는 방법을 보여줍니다. 파라미터 매핑을 사용하여 필요한 CORS 헤더를 만드는 방법의 예제는 [API Gateway의 REST API CORS](how-to-cors.md) 섹션을 참조하시기 바랍니다.

## 예제 1: 메서드 요청 파라미터를 통합 요청 파라미터에 매핑
<a name="request-response-data-mappings-example-1"></a>

다음 예제에서는 메서드 요청 헤더 파라미터(`puppies`)를 통합 요청 헤더 파라미터(`DogsAge0`)에 매핑합니다.

------
#### [ AWS Management Console ]

**메서드 요청 파라미터 매핑**

1. [https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)에서 API Gateway 콘솔에 로그인합니다.

1. REST API를 선택합니다.

1. 방법을 선택합니다.

   메서드에는 비프록시 통합이 있어야 합니다.

1. **메서드 요청 설정** 섹션에서 **편집**을 선택합니다.

1. **HTTP 요청 헤더**를 선택합니다.

1. **헤더 추가(Add header)**를 선택합니다.

1. **이름**에 **puppies**를 입력합니다.

1. **저장**을 선택합니다.

1. **통합 요청** 탭을 선택한 다음 **통합 요청 설정**에서 **편집**을 선택합니다.

   AWS Management Console은 `method.request.header.puppies `에서 `puppies`로 파라미터 매핑을 자동으로 추가하지만 통합 엔드포인트에서 예상되는 요청 헤더 파라미터와 일치하도록 **이름**을 변경해야 합니다.

1. **이름**에 **DogsAge0**를 입력합니다.

1. **저장**을 선택합니다.

1. 변경 사항을 적용하려면 API를 재배포합니다.

다음 단계에서는 파라미터 매핑이 성공했는지 확인하는 방법을 보여줍니다.

**(선택 사항) 파라미터 매핑 테스트**

1. **테스트** 탭을 선택합니다. 탭을 표시하려면 오른쪽 화살표 버튼을 선택해야 할 수도 있습니다.

1. 헤더에 **puppies:true**를 입력합니다.

1. **테스트**를 선택합니다.

1. **로그**에 다음과 같은 결과가 표시되어야 합니다.

   ```
   Tue Feb 04 00:28:36 UTC 2025 : Method request headers: {puppies=true}
   Tue Feb 04 00:28:36 UTC 2025 : Method request body before transformations: 
   Tue Feb 04 00:28:36 UTC 2025 : Endpoint request URI: http://petstore-demo-endpoint.execute-api.com/petstore/pets
   Tue Feb 04 00:28:36 UTC 2025 : Endpoint request headers: {DogsAge0=true, x-amzn-apigateway-api-id=abcd1234, Accept=application/json, User-Agent=AmazonAPIGateway_aaaaaaa, X-Amzn-Trace-Id=Root=1-abcd-12344}
   ```

   요청 헤더 파라미터가 `puppies`에서 `DogsAge0`으로 변경되었습니다.

------
#### [ CloudFormation ]

 이 예제에서는 [본문](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-body) 속성을 사용하여 OpenAPI 정의 파일을 API Gateway로 가져옵니다.

```
AWSTemplateFormatVersion: 2010-09-09
Resources:
  Api:
    Type: 'AWS::ApiGateway::RestApi'
    Properties:
      Body:
        openapi: 3.0.1
        info:
          title: ParameterMappingExample
          version: "2025-02-04T00:30:41Z"
        paths:
          /pets:
            get:
              parameters:
                - name: puppies
                  in: header
                  schema:
                    type: string
              responses:
                "200":
                  description: 200 response
              x-amazon-apigateway-integration:
                httpMethod: GET
                uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets
                responses:
                  default:
                    statusCode: "200"
                requestParameters:
                  integration.request.header.DogsAge0: method.request.header.puppies
                passthroughBehavior: when_no_match
                type: http
  ApiGatewayDeployment:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn: Api 
    Properties: 
      RestApiId: !Ref Api
  ApiGatewayDeployment20250219:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn: Api 
    Properties: 
      RestApiId: !Ref Api
  Stage:
    Type: 'AWS::ApiGateway::Stage'
    Properties:
       DeploymentId: !Ref ApiGatewayDeployment20250219
       RestApiId: !Ref Api
       StageName: prod
```

------
#### [ OpenAPI ]

```
{
  "openapi" : "3.0.1",
  "info" : {
    "title" : "ParameterMappingExample",
    "version" : "2025-02-04T00:30:41Z"
  },
  "paths" : {
    "/pets" : {
      "get" : {
        "parameters" : [ {
          "name" : "puppies",
          "in" : "header",
          "schema" : {
            "type" : "string"
          }
        } ],
        "responses" : {
          "200" : {
            "description" : "200 response"
          }
        },
        "x-amazon-apigateway-integration" : {
          "httpMethod" : "GET",
          "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets",
          "responses" : {
            "default" : {
              "statusCode" : "200"
            }
          },
          "requestParameters" : {
            "integration.request.header.DogsAge0" : "method.request.header.puppies"
          },
          "passthroughBehavior" : "when_no_match",
          "type" : "http"
        }
      }
    }
  }
}
```

------

## 예제 2: 여러 메서드 요청 파라미터를 다른 통합 요청 파라미터에 매핑
<a name="request-response-data-mappings-example-2"></a>

다음 예제에서는 다중 값 메서드 요청 쿼리 문자열 파라미터(`methodRequestQueryParam`)를 통합 요청 쿼리 문자열 파라미터(`integrationQueryParam`)에 매핑하고 메서드 요청 헤더 파라미터(`methodRequestHeaderParam`)를 통합 요청 경로 파라미터(`integrationPathParam`)에 매핑합니다.

------
#### [ AWS Management Console ]

**메서드 요청 파라미터 매핑**

1. [https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)에서 API Gateway 콘솔에 로그인합니다.

1. REST API를 선택합니다.

1. 방법을 선택합니다.

   메서드에는 비프록시 통합이 있어야 합니다.

1. **메서드 요청 설정** 섹션에서 **편집**을 선택합니다.

1. **URL 쿼리 문자열 파라미터**를 선택합니다.

1. **쿼리 문자열 추가(Add query string)**를 선택합니다.

1. **이름**에 **methodRequestQueryParam**를 입력합니다.

1. **HTTP 요청 헤더**를 선택합니다.

1. **헤더 추가(Add header)**를 선택합니다.

1. **이름**에 **methodRequestHeaderParam**를 입력합니다.

1. **저장**을 선택합니다.

1. **통합 요청** 탭을 선택한 다음 **통합 요청 설정**에서 **편집**을 선택합니다.

1. **URL 경로 파라미터**를 선택합니다.

1. **경로 파라미터 추가**를 선택합니다.

1. **이름**에 **integrationPathParam**를 입력합니다.

1. **다음에서 매핑됨**에 **method.request.header.methodRequestHeaderParam**을 입력합니다.

   그러면 메서드 요청에서 지정한 메서드 요청 헤더가 새 통합 요청 경로 파라미터에 매핑됩니다.

1. **URL 쿼리 문자열 파라미터**를 선택합니다.

1. **쿼리 문자열 추가(Add query string)**를 선택합니다.

1. **이름**에 **integrationQueryParam**를 입력합니다.

1. **다음에서 매핑됨**에 **method.request.multivaluequerystring.methodRequestQueryParam**을 입력합니다.

   그러면 다중 값 쿼리 문자열 파라미터가 새로운 단일 값 통합 요청 쿼리 문자열 파라미터에 매핑됩니다.

1. **저장**을 선택합니다.

1. 변경 사항을 적용하려면 API를 재배포합니다.

------
#### [ CloudFormation ]

 이 예제에서는 [본문](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-body) 속성을 사용하여 OpenAPI 정의 파일을 API Gateway로 가져옵니다.

다음 OpenAPI 정의는 HTTP 통합에 대해 다음과 같은 파라미터 매핑을 만듭니다.
+ `methodRequestHeaderParam`이라는 메서드 요청 헤더를 `integrationPathParam`이라는 통합 요청 경로 파라미터로 매핑합니다.
+ `methodRequestQueryParam`이라는 다중 값 메서드 요청 쿼리 문자열은 `integrationQueryParam`이라는 통합 요청 쿼리 문자열에 매핑됩니다.

```
AWSTemplateFormatVersion: 2010-09-09
Resources:
  Api:
    Type: 'AWS::ApiGateway::RestApi'
    Properties:
      Body: 
        openapi: 3.0.1
        info:
          title: Parameter mapping example 2
          version: "2025-01-15T19:12:31Z"
        paths:
          /:
            post:
              parameters:
                - name: methodRequestQueryParam
                  in: query
                  schema:
                    type: string
                - name: methodRequestHeaderParam
                  in: header
                  schema:
                    type: string
              responses:
                "200":
                  description: 200 response
              x-amazon-apigateway-integration:
                httpMethod: GET
                uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets
                responses:
                  default:
                    statusCode: "200"
                requestParameters:
                  integration.request.querystring.integrationQueryParam: method.request.multivaluequerystring.methodRequestQueryParam
                  integration.request.path.integrationPathParam: method.request.header.methodRequestHeaderParam
                requestTemplates:
                  application/json: '{"statusCode": 200}'
                passthroughBehavior: when_no_templates
                timeoutInMillis: 29000
                type: http
  ApiGatewayDeployment:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn: Api 
    Properties: 
      RestApiId: !Ref Api
  ApiGatewayDeployment20250219:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn: Api 
    Properties: 
      RestApiId: !Ref Api
  Stage:
    Type: 'AWS::ApiGateway::Stage'
    Properties:
       DeploymentId: !Ref ApiGatewayDeployment20250219
       RestApiId: !Ref Api
       StageName: prod
```

------
#### [ OpenAPI ]

다음 OpenAPI 정의는 HTTP 통합에 대해 다음과 같은 파라미터 매핑을 만듭니다.
+ `methodRequestHeaderParam`이라는 메서드 요청 헤더를 `integrationPathParam`이라는 통합 요청 경로 파라미터로 매핑합니다.
+ `methodRequestQueryParam`이라는 다중 값 메서드 요청 쿼리 문자열은 `integrationQueryParam`이라는 통합 요청 쿼리 문자열에 매핑됩니다.

```
{
  "openapi" : "3.0.1",
  "info" : {
    "title" : "Parameter mapping example 2",
    "version" : "2025-01-15T19:12:31Z"
  },
  "paths" : {
    "/" : {
      "post" : {
        "parameters" : [ {
          "name" : "methodRequestQueryParam",
          "in" : "query",
          "schema" : {
            "type" : "string"
          }
        }, {
          "name" : "methodRequestHeaderParam",
          "in" : "header",
          "schema" : {
            "type" : "string"
          }
        } ],
        "responses" : {
          "200" : {
            "description" : "200 response"
          }
        },
        "x-amazon-apigateway-integration" : {
          "httpMethod" : "GET",
          "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets",
          "responses" : {
            "default" : {
              "statusCode" : "200"
            }
          },
          "requestParameters" : {
            "integration.request.querystring.integrationQueryParam" : "method.request.multivaluequerystring.methodRequestQueryParam",
            "integration.request.path.integrationPathParam" : "method.request.header.methodRequestHeaderParam"
          },
          "requestTemplates" : {
            "application/json" : "{\"statusCode\": 200}"
          },
          "passthroughBehavior" : "when_no_templates",
          "timeoutInMillis" : 29000,
          "type" : "http"
        }
      }
    }
  }
}
```

------

## 예제 3: JSON 요청 본문의 필드를 통합 요청 파라미터에 매핑
<a name="request-response-data-mappings-example-3"></a>

또한 [JSONPath 표현식](http://goessner.net/articles/JsonPath/index.html#e2)을 사용하여 JSON 요청 본문의 필드에서 통합 요청 파라미터를 매핑할 수 있습니다. 다음 예제에서는 메서드 요청 본문을 `body-header`라는 통합 요청 헤더에 매핑하고 JSON 표현식으로 표현되는 요청 본문의 일부를 `pet-price`라는 통합 요청 헤더에 매핑합니다.

이 예제를 테스트하려면 다음과 같이 가격 범주가 포함된 입력을 제공합니다.

```
[ 
  { 
    "id": 1, 
    "type": "dog", 
    "price": 249.99 
  }
]
```

------
#### [ AWS Management Console ]

**메서드 요청 파라미터 매핑**

1. [https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)에서 API Gateway 콘솔에 로그인합니다.

1. REST API를 선택합니다.

1. `POST`, `PUT`, `PATCH` 또는 `ANY` 메서드를 선택합니다.

   메서드에는 비프록시 통합이 있어야 합니다.

1. **통합 요청 설정**에서 **편집**을 선택합니다.

1. **요청 헤더 파라미터**를 선택합니다.

1. **요청 헤더 파라미터 추가**를 선택합니다.

1. **이름**에 **body-header**를 입력합니다.

1. **다음에서 매핑됨**에 **method.request.body**을 입력합니다.

   그러면 메서드 요청 본문이 새 통합 요청 헤더 파라미터에 매핑됩니다.

1. **요청 헤더 파라미터 추가**를 선택합니다.

1. **이름**에 **pet-price**를 입력합니다.

1. **다음에서 매핑됨**에 ** method.request.body[0].price**을 입력합니다.

   그러면 메서드 요청 본문의 일부가 새 통합 요청 헤더 파라미터에 매핑됩니다.

1. **저장**을 선택합니다.

1. 변경 사항을 적용하려면 API를 재배포합니다.

------
#### [ CloudFormation ]

 이 예제에서는 [본문](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-body) 속성을 사용하여 OpenAPI 정의 파일을 API Gateway로 가져옵니다.

```
AWSTemplateFormatVersion: 2010-09-09
Resources:
  Api:
    Type: 'AWS::ApiGateway::RestApi'
    Properties:
      Body: 
        openapi: 3.0.1
        info:
          title: Parameter mapping example 3
          version: "2025-01-15T19:19:14Z"
        paths:
          /:
            post:
              responses:
                "200":
                  description: 200 response
              x-amazon-apigateway-integration:
                httpMethod: GET
                uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets
                responses:
                  default:
                    statusCode: "200"
                requestParameters:
                  integration.request.header.pet-price: method.request.body[0].price
                  integration.request.header.body-header: method.request.body
                requestTemplates:
                  application/json: '{"statusCode": 200}'
                passthroughBehavior: when_no_templates
                timeoutInMillis: 29000
                type: http
  ApiGatewayDeployment:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn: Api 
    Properties: 
      RestApiId: !Ref Api
  ApiGatewayDeployment20250219:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn: Api 
    Properties: 
      RestApiId: !Ref Api
  Stage:
    Type: 'AWS::ApiGateway::Stage'
    Properties:
       DeploymentId: !Ref ApiGatewayDeployment20250219
       RestApiId: !Ref Api
       StageName: prod
```

------
#### [ OpenAPI ]

다음 OpenAPI 정의는 JSON 요청 본문의 필드에서 통합 요청 파라미터를 매핑합니다.

```
{
  "openapi" : "3.0.1",
  "info" : {
    "title" : "Parameter mapping example 3",
    "version" : "2025-01-15T19:19:14Z"
  },
  "paths" : {
    "/" : {
      "post" : {
        "responses" : {
          "200" : {
            "description" : "200 response"
          }
        },
        "x-amazon-apigateway-integration" : {
          "httpMethod" : "GET",
          "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets",
          "responses" : {
            "default" : {
              "statusCode" : "200"
            }
          },
          "requestParameters" : {
            "integration.request.header.pet-price" : "method.request.body[0].price",
            "integration.request.header.body-header" : "method.request.body"
          },
          "requestTemplates" : {
            "application/json" : "{\"statusCode\": 200}"
          },
          "passthroughBehavior" : "when_no_templates",
          "timeoutInMillis" : 29000,
          "type" : "http"
        }
      }
    }
  }
}
```

------

## 예제 4: 통합 응답을 메서드 응답에 매핑
<a name="request-response-data-mappings-example-4"></a>

또한 통합 응답을 메서드 응답에 매핑할 수 있습니다. 다음 예제에서는 통합 응답 본문을 `location`이라는 메서드 응답 헤더에 매핑하고, 통합 응답 헤더(`x-app-id`)를 메서드 응답 헤더(`id`)에 매핑하고, 다중 값 통합 응답 헤더(`item`)를 메서드 응답 헤더(`items`)에 매핑합니다.

------
#### [ AWS Management Console ]

**통합 응답 매핑**

1. [https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)에서 API Gateway 콘솔에 로그인합니다.

1. REST API를 선택합니다.

1. 방법을 선택합니다.

   메서드에는 비프록시 통합이 있어야 합니다.

1. **메서드 응답** 탭을 선택한 다음 **응답 200**에서 **편집**을 선택합니다.

1. **헤더 이름**에서 **헤더 추가**를 선택합니다.

1. **id**, **item** 및 **location**이라는 헤더 3개를 만듭니다.

1. **저장**을 선택합니다.

1. **통합 응답** 탭을 선택한 다음, **기본값 - 응답**에서 **편집**을 선택합니다.

1. **헤더 매핑** 아래에서 다음을 입력합니다.

   1. **id**에 **integration.response.header.x-app-id**를 입력합니다.

   1. **항목**에 **integration.response.multivalueheader.item**을 입력합니다.

   1. **위치**에 **integration.response.body.redirect.url**을 입력합니다.

1. **저장**을 선택합니다.

1. 변경 사항을 적용하려면 API를 재배포합니다.

------
#### [ CloudFormation ]

 이 예제에서는 [본문](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-body) 속성을 사용하여 OpenAPI 정의 파일을 API Gateway로 가져옵니다.

```
AWSTemplateFormatVersion: 2010-09-09
Resources:
  Api:
    Type: 'AWS::ApiGateway::RestApi'
    Properties:
      Body:
        openapi: 3.0.1
        info:
          title: Parameter mapping example
          version: "2025-01-15T19:21:35Z"
        paths:
          /:
            post:
              responses:
                "200":
                  description: 200 response
                  headers:
                    item:
                      schema:
                        type: string
                    location:
                      schema:
                        type: string
                    id:
                      schema:
                        type: string
              x-amazon-apigateway-integration:
                type: http
                httpMethod: GET
                uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets
                responses:
                  default:
                    statusCode: "200"
                    responseParameters:
                      method.response.header.id: integration.response.header.x-app-id
                      method.response.header.location: integration.response.body.redirect.url
                      method.response.header.item: integration.response.multivalueheader.item
                requestTemplates:
                  application/json: '{"statusCode": 200}'
                passthroughBehavior: when_no_templates
                timeoutInMillis: 29000
  ApiGatewayDeployment:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn: Api 
    Properties: 
      RestApiId: !Ref Api
  ApiGatewayDeployment20250219:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn: Api 
    Properties: 
      RestApiId: !Ref Api
  Stage:
    Type: 'AWS::ApiGateway::Stage'
    Properties:
       DeploymentId: !Ref ApiGatewayDeployment20250219
       RestApiId: !Ref Api
       StageName: prod
```

------
#### [ OpenAPI ]

다음 OpenAPI 정의는 통합 응답을 메서드 응답에 매핑합니다.

```
{
  "openapi" : "3.0.1",
  "info" : {
    "title" : "Parameter mapping example",
    "version" : "2025-01-15T19:21:35Z"
  },
  "paths" : {
    "/" : {
      "post" : {
        "responses" : {
          "200" : {
            "description" : "200 response",
            "headers" : {
              "item" : {
                "schema" : {
                  "type" : "string"
                }
              },
              "location" : {
                "schema" : {
                  "type" : "string"
                }
              },
              "id" : {
                "schema" : {
                  "type" : "string"
                }
              }
            }
          }
        },
        "x-amazon-apigateway-integration" : {
          "type" : "http",
          "httpMethod" : "GET",
          "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets",
          "responses" : {
            "default" : {
              "statusCode" : "200",
              "responseParameters" : {
                "method.response.header.id" : "integration.response.header.x-app-id",
                "method.response.header.location" : "integration.response.body.redirect.url",
                "method.response.header.item" : "integration.response.multivalueheader.item"
              }
            }
          },
          "requestTemplates" : {
            "application/json" : "{\"statusCode\": 200}"
          },
          "passthroughBehavior" : "when_no_templates",
          "timeoutInMillis" : 29000
        }
      }
    }
  }
}
```

------

# API Gateway의 REST API에 대한 파라미터 매핑 소스 참조
<a name="rest-api-parameter-mapping-sources"></a>

파라미터 매핑을 만들 경우 수정할 메서드 요청 또는 통합 응답 파라미터를 지정하고 이러한 파라미터를 수정하는 방법을 지정합니다.

다음 표에는 매핑할 수 있는 메서드 요청 파라미터와 매핑을 만드는 표현식이 나와 있습니다. 이러한 표현식에서 *name*은 메서드 요청 파라미터의 이름입니다. 예를 들어 요청 헤더 파라미터(`puppies`)를 매핑하려면 `method.request.header.puppies` 표현식을 사용합니다. 표현식은 `'^[a-zA-Z0-9._$-]+$]'` 정규 표현식과 일치해야 합니다. 프록시 및 비 프록시 통합에 대한 통합 요청에서 파라미터 매핑을 사용할 수 있습니다.


| **매핑된 데이터 소스** | **매핑 표현식** | 
| --- | --- | 
| 메서드 요청 경로 | method.request.path.name | 
| 메서드 요청 쿼리 문자열 | method.request.querystring.name | 
| 다중 값 메서드 요청 쿼리 문자열 | method.request.multivaluequerystring.name | 
| 메서드 요청 헤더 | method.request.header.name | 
| 다중 값 메서드 요청 헤더 | method.request.multivalueheader.name | 
| 메서드 요청 본문 | method.request.body | 
| 메서드 요청 본문(JsonPath) | `method.request.body.JSONPath_EXPRESSION`. *JSONPath\$1EXPRESSION*은 요청 본문의 JSON 필드에 대한 JSONPath 표현식입니다. 자세한 내용은 [JSONPath 표현식](http://goessner.net/articles/JsonPath/index.html#e2)을 참조하시기 바랍니다.  | 
| 단계 변수 | stageVariables.name | 
| 컨텍스트 변수 |  `context.name` 이름은 [지원되는 컨텍스트 변수](api-gateway-mapping-template-reference.md#context-variable-reference) 중 하나여야 합니다. | 
| 정적 값 | `'static_value'`. *static\$1value*는 문자열 리터럴이며 작은따옴표 쌍으로 묶여야 합니다. 예를 들어 `'https://www.example.com'`입니다. | 

다음 표에는 매핑할 수 있는 통합 응답 파라미터와 매핑을 만드는 표현식이 나와 있습니다. 이러한 표현식에서 *name*은 통합 응답 파라미터의 이름입니다. 통합 응답 헤더 또는 통합 응답 본문, \$1context 변수 또는 정적 값에서 메서드 응답 헤더를 매핑할 수 있습니다. 통합 응답에 파라미터 매핑을 사용하려면 비 프록시 통합이 필요합니다.


| 매핑된 데이터 원본 | 매핑 표현식 | 
| --- | --- | 
| 통합 응답 헤더 | integration.response.header.name | 
| 통합 응답 헤더 | integration.response.multivalueheader.name | 
| 통합 응답 본문 | integration.response.body | 
| 통합 응답 본문(JsonPath) | `integration.response.body.JSONPath_EXPRESSION` *JSONPath\$1EXPRESSION*은 응답 본문의 JSON 필드에 대한 JSONPath 표현식입니다. 자세한 내용은 [JSONPath 표현식](http://goessner.net/articles/JsonPath/index.html#e2)을 참조하시기 바랍니다. | 
| 단계 변수 | stageVariables.name | 
| 컨텍스트 변수 |  `context.name` 이름은 [지원되는 컨텍스트 변수](api-gateway-mapping-template-reference.md#context-variable-reference) 중 하나여야 합니다. | 
| 정적 값 | ` 'static_value'` *static\$1value*는 문자열 리터럴이며 작은따옴표 쌍으로 묶여야 합니다. 예를 들어 `'https://www.example.com'`입니다. | 

# API Gateway에서 REST API의 데이터 변환 매핑
<a name="models-mappings"></a>

매핑 템플릿 변환은 매핑 템플릿을 사용하여 통합 요청 또는 통합 응답을 수정합니다. *매핑 템플릿*이란 [Velocity Template Language(VTL)](https://velocity.apache.org/engine/devel/vtl-reference.html)로 표현된 스크립트로, [JSONPath](https://goessner.net/articles/JsonPath/)를 사용하여 `Content-type` 헤더 기반 페이로드에 적용됩니다. 매핑 템플릿 변환을 사용할 경우 매핑 템플릿을 사용합니다. 이 섹션에서는 매핑 템플릿과 관련된 개념 정보를 설명합니다.

다음 다이어그램은 PetStore 통합 엔드포인트와 통합된 `POST /pets` 리소스의 요청 수명 주기를 보여줍니다. 이 API에서 사용자는 반려동물에 대한 데이터를 전송하고 통합 엔드포인트는 반려동물과 관련된 입양 요금을 반환합니다. 이 요청 수명 주기에서 매핑 템플릿 변환은 요청 본문을 통합 엔드포인트로 필터링하고 통합 엔드포인트에서 응답 본문을 필터링합니다.

![\[요청 수명 주기 예제\]](http://docs.aws.amazon.com/ko_kr/apigateway/latest/developerguide/images/mapping-template-transforms.png)


다음 섹션에서는 요청 및 응답 수명 주기를 설명합니다.

## 메서드 요청 및 통합 요청
<a name="models-mappings-request"></a>

이전 예제에서 메서드 요청으로 전송된 요청 본문인 경우:

```
POST /pets
    HTTP/1.1
    Host:abcd1234.us-west-2.amazonaws.com
    Content-type: application/json
    
  {
    "id": 1,
    "type": "dog",
    "Age": 11,
  }
```

이 요청 본문은 통합 엔드포인트에서 사용할 올바른 형식이 아니므로 API Gateway는 매핑 템플릿 변환을 수행합니다. API Gateway는 콘텐츠 유형 `application/json`에 대해 정의된 매핑 템플릿이 있으므로 매핑 템플릿 변환만 수행합니다. 콘텐츠 유형에 대한 매핑 템플릿을 정의하지 않으면 기본적으로 API Gateway는 통합 요청을 통해 본문을 통합 엔드포인트로 전달합니다. 이 동작을 수정하려면 [API Gateway의 REST API에 대한 매핑 템플릿이 없는 페이로드의 메서드 요청 동작](integration-passthrough-behaviors.md) 섹션을 참조하시기 바랍니다.

다음 매핑 템플릿은 통합 엔드포인트로 전송되기 전에 통합 요청의 메서드 요청 데이터를 변환합니다.

```
#set($inputRoot = $input.path('$'))
  {
    "dogId" : "dog_"$elem.id,
    "Age": $inputRoot.Age
  }
```

1. `$inputRoot` 변수는 이전 단원에서 다룬 원본 JSON 데이터의 루트 객체를 나타냅니다. 지시어는 `#` 기호로 시작됩니다.

1. `dog`는 사용자의 `id`와 문자열 값의 연결입니다.

1. `Age`는 메서드 요청 본문에서 가져온 것입니다.

그런 다음, 다음 출력이 통합 엔드포인트로 전달됩니다.

```
{
    "dogId" : "dog_1",
    "Age": 11
  }
```

## 통합 응답 및 메서드 응답
<a name="models-mappings-response"></a>

통합 엔드포인트에 대한 요청이 성공하면 엔드포인트는 API Gateway의 통합 응답에 응답을 보냅니다. 다음은 통합 엔드포인트의 예제 출력 데이터입니다.

```
{
    "dogId" : "dog_1",
    "adoptionFee": 19.95,
}
```

메서드 응답은 통합 응답에서 반환되는 것과 다른 페이로드를 예상합니다. API Gateway는 매핑 템플릿 변환을 수행합니다. API Gateway는 콘텐츠 유형 `application/json`에 대해 정의된 매핑 템플릿이 있으므로 매핑 템플릿 변환만 수행합니다. 콘텐츠 유형에 대한 매핑 템플릿을 정의하지 않으면 기본적으로 API Gateway는 메서드 응답을 통해 통합 응답으로 본문을 전달합니다. 이 동작을 수정하려면 [API Gateway의 REST API에 대한 매핑 템플릿이 없는 페이로드의 메서드 요청 동작](integration-passthrough-behaviors.md) 섹션을 참조하시기 바랍니다.

```
#set($inputRoot = $input.path('$'))
  {
    "adoptionFee" : $inputRoot.adoptionFee,
  }
```

다음은 메서드 응답으로 전송된 출력입니다.

```
{"adoptionFee": 19.95}
```

그러면 예제 매핑 템플릿 변환이 완료됩니다. 가능하면 매핑 템플릿 변환을 사용하는 대신 프록시 통합을 사용하여 데이터를 변환하는 것이 좋습니다. 자세한 내용은 [API Gateway API 통합 유형 선택](api-gateway-api-integration-types.md) 섹션을 참조하세요.

# API Gateway의 REST API에 대한 매핑 템플릿이 없는 페이로드의 메서드 요청 동작
<a name="integration-passthrough-behaviors"></a>

메서드 요청에 페이로드가 있고 `Content-Type` 헤더에 대해 정의된 매핑 템플릿이 없는 경우 변환 없이 통합 요청을 통해 클라이언트가 제공한 요청 페이로드를 백엔드로 전달하도록 선택할 수 있습니다. 이 프로세스를 통합 패스스루라고 합니다.

 수신 요청의 실제 패스스루 동작은 이 설정에 따라 결정됩니다. 여기에는 다음과 같은 세 가지 옵션이 있습니다.

**요청 Content-Type 헤더와 일치하는 템플릿이 없는 경우**  
메서드 요청 콘텐츠 유형이 매핑 템플릿과 연결된 콘텐츠 유형 중 일치하지 않는 경우 메서드 요청 본문이 변환 없이 통합 요청을 지나 백엔드에 전달되도록 하려면 이 옵션을 선택합니다.  
API Gateway API를 호출하는 경우 이 옵션을 선택하려면 [통합](https://docs.aws.amazon.com/apigateway/latest/api/API_Integration.html)에서 `WHEN_NO_MATCH`를 `passthroughBehavior` 속성 값으로 설정하면 됩니다.

**정의된 템플릿이 없는 경우(권장)**  
매핑 템플릿이 통합 요청에 정의되어 있지 않을 때 메서드 요청 본문이 변환 없이 통합 요청을 지나 벡엔드에 전달되도록 하려면 이 옵션을 선택합니다. 이 옵션을 선택할 때 템플릿이 정의되어 있는 경우 정의된 매핑 템플릿과 일치하지 않은 페이로드와 콘텐츠 유형이 있는 메서드 요청은 HTTP 415 미지원 미디어 유형 응답과 함께 거부됩니다.  
API Gateway API를 호출하는 경우 이 옵션을 선택하려면 [통합](https://docs.aws.amazon.com/apigateway/latest/api/API_Integration.html)에서 `WHEN_NO_TEMPLATES`를 `passthroughBehavior` 속성 값으로 설정하면 됩니다.

**없음**  
매핑 템플릿이 통합 요청에 정의되어 있지 않을 때 메서드 요청 본문이 변환 없이 통합 요청을 지나 벡엔드에 전달되지 않도록 하려면 이 옵션을 선택합니다. 이 옵션을 선택할 때 템플릿이 정의되어 있는 경우 매핑되지 않은 콘텐츠 유형의 메서드 요청은 HTTP 415 미지원 미디어 유형 응답과 함께 거부됩니다.  
API Gateway API를 호출하는 경우 이 옵션을 선택하려면 [통합](https://docs.aws.amazon.com/apigateway/latest/api/API_Integration.html)에서 `NEVER`를 `passthroughBehavior` 속성 값으로 설정하면 됩니다.

 다음 예제에서는 가능한 패스스루 동작을 설명합니다.

예제 1: 하나의 매핑 템플릿이 `application/json` 콘텐츠 유형에 대한 통합 요청에 정의되어 있습니다.


| 콘텐츠 유형 | 패스스루 옵션 | 동작 | 
| --- | --- | --- | 
| 없음 API Gateway의 기본값은 `application/json`입니다. | WHEN\$1NO\$1MATCH | 템플릿을 사용하여 요청 페이로드가 변환됩니다. | 
| 없음 API Gateway의 기본값은 `application/json`입니다. | WHEN\$1NO\$1TEMPLATES | 템플릿을 사용하여 요청 페이로드가 변환됩니다. | 
| 없음 API Gateway의 기본값은 `application/json`입니다. | NEVER | 템플릿을 사용하여 요청 페이로드가 변환됩니다. | 
| application/json | WHEN\$1NO\$1MATCH | 템플릿을 사용하여 요청 페이로드가 변환됩니다. | 
| application/json | WHEN\$1NO\$1TEMPLATES | 템플릿을 사용하여 요청 페이로드가 변환됩니다. | 
| application/json | NEVER | 템플릿을 사용하여 요청 페이로드가 변환됩니다. | 
| application/xml | WHEN\$1NO\$1MATCH | 요청 페이로드가 변환되지 않고 백엔드로 그대로 전송됩니다. | 
| application/xml | WHEN\$1NO\$1TEMPLATES | 요청이 HTTP 415 Unsupported Media Type 응답과 함께 거부됩니다. | 
| application/xml | NEVER | 요청이 HTTP 415 Unsupported Media Type 응답과 함께 거부됩니다. | 

예제 2: 하나의 매핑 템플릿이 `application/xml` 콘텐츠 유형에 대한 통합 요청에 정의되어 있습니다.


| 콘텐츠 유형 | 패스스루 옵션 | 동작 | 
| --- | --- | --- | 
| 없음 API Gateway의 기본값은 `application/json`입니다. | WHEN\$1NO\$1MATCH | 요청 페이로드가 변환되지 않고 백엔드로 그대로 전송됩니다. | 
| 없음 API Gateway의 기본값은 `application/json`입니다. | WHEN\$1NO\$1TEMPLATES | 요청이 HTTP 415 Unsupported Media Type 응답과 함께 거부됩니다. | 
| 없음 API Gateway의 기본값은 `application/json`입니다. | NEVER | 요청이 HTTP 415 Unsupported Media Type 응답과 함께 거부됩니다. | 
| application/json | WHEN\$1NO\$1MATCH | 요청 페이로드가 변환되지 않고 백엔드로 그대로 전송됩니다. | 
| application/json | WHEN\$1NO\$1TEMPLATES | 요청이 HTTP 415 Unsupported Media Type 응답과 함께 거부됩니다. | 
| application/json | NEVER | 요청이 HTTP 415 Unsupported Media Type 응답과 함께 거부됩니다. | 
| application/xml | WHEN\$1NO\$1MATCH | 템플릿을 사용하여 요청 페이로드가 변환됩니다. | 
| application/xml | WHEN\$1NO\$1TEMPLATES | 템플릿을 사용하여 요청 페이로드가 변환됩니다. | 
| application/xml | NEVER | 템플릿을 사용하여 요청 페이로드가 변환됩니다. | 

예제 3: 통합 요청에 매핑 템플릿이 정의되지 않았습니다.


| 콘텐츠 유형 | 패스스루 옵션 | 동작 | 
| --- | --- | --- | 
| 없음 API Gateway의 기본값은 `application/json`입니다. | WHEN\$1NO\$1MATCH | 요청 페이로드가 변환되지 않고 백엔드로 그대로 전송됩니다. | 
| 없음 API Gateway의 기본값은 `application/json`입니다. | WHEN\$1NO\$1TEMPLATES | 요청 페이로드가 변환되지 않고 백엔드로 그대로 전송됩니다. | 
| 없음 API Gateway의 기본값은 `application/json`입니다. | NEVER | 요청이 HTTP 415 Unsupported Media Type 응답과 함께 거부됩니다. | 
| application/json | WHEN\$1NO\$1MATCH | 요청 페이로드가 변환되지 않고 백엔드로 그대로 전송됩니다. | 
| application/json | WHEN\$1NO\$1TEMPLATES | 요청 페이로드가 변환되지 않고 백엔드로 그대로 전송됩니다. | 
| application/json | NEVER | 요청이 HTTP 415 Unsupported Media Type 응답과 함께 거부됩니다. | 
| application/xml | WHEN\$1NO\$1MATCH | 요청 페이로드가 변환되지 않고 백엔드로 그대로 전송됩니다. | 
| application/xml | WHEN\$1NO\$1TEMPLATES | 요청 페이로드가 변환되지 않고 백엔드로 그대로 전송됩니다. | 
| application/xml | NEVER | 요청이 HTTP 415 Unsupported Media Type 응답과 함께 거부됩니다. | 

# API Gateway의 REST API에 대한 추가 매핑 템플릿 예제
<a name="example-photos"></a>

다음 예제는 매핑 템플릿을 사용하여 통합 요청 및 통합 응답 데이터를 변환하는 API Gateway의 사진 앨범 API를 보여줍니다. 또한 데이터 모델을 사용하여 메서드 요청 및 통합 응답 페이로드를 정의합니다. 데이터 모델에 대한 자세한 내용은 [REST API에 대한 데이터 모델](models-mappings-models.md) 섹션을 참조합니다.

## 메서드 요청 및 통합 요청
<a name="example-photos-request"></a>

다음은 메서드 요청 본문을 정의하는 모델입니다. 이 입력 모델에는 한 장의 사진을 업로드해야 하며 각 페이지당 사진 수가 최소 10장으로 지정되어 있습니다. 이 입력 모델을 사용하여 SDK를 생성하거나 API에 대한 요청 확인을 사용할 수 있습니다. 요청 검증을 사용하는 동안 메서드 요청 본문이 모델의 데이터 구조를 준수하지 않으면 API Gateway에서 요청이 실패됩니다.

```
{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "PhotosInputModel",
  "type": "object",
  "properties": {
    "photos": {
      "type": "object",
      "required" : [
      "photo"
      ],
      "properties": {
        "page": { "type": "integer" },
        "pages": { "type": "string" },
        "perpage": { "type": "integer", "minimum" : 10 },
        "total": { "type": "string" },
        "photo": {
          "type": "array",
          "items": {
            "type": "object",
            "properties": {
              "id": { "type": "string" },
              "owner": { "type": "string" },
              "photographer_first_name" : {"type" : "string"},
              "photographer_last_name" : {"type" : "string"},
              "secret": { "type": "string" },
              "server": { "type": "string" },
              "farm": { "type": "integer" },
              "title": { "type": "string" },
              "ispublic": { "type": "boolean" },
              "isfriend": { "type": "boolean" },
              "isfamily": { "type": "boolean" }
            }
          }
        }
      }
    }
  }
}
```

다음은 이전 데이터 모델의 데이터 구조를 준수하는 메서드 요청 본문의 예제입니다.

```
{
  "photos": {
    "page": 1,
    "pages": "1234",
    "perpage": 100,
    "total": "123398",
    "photo": [
      {
        "id": "12345678901",
        "owner": "23456789@A12",
        "photographer_first_name" : "Saanvi",
        "photographer_last_name" : "Sarkar",
        "secret": "abc123d456",
        "server": "1234",
        "farm": 1,
        "title": "Sample photo 1",
        "ispublic": true,
        "isfriend": false,
        "isfamily": false
      },
      {
        "id": "23456789012",
        "owner": "34567890@B23",
        "photographer_first_name" : "Richard",
        "photographer_last_name" : "Roe",
        "secret": "bcd234e567",
        "server": "2345",
        "farm": 2,
        "title": "Sample photo 2",
        "ispublic": true,
        "isfriend": false,
        "isfamily": false
      }
    ]
  }
}
```

이 예제에서는 클라이언트가 이전 메서드 요청 본문을 제출한 경우 이 매핑 템플릿은 통합 엔드포인트에 필요한 형식과 일치하도록 페이로드를 변환합니다.

```
#set($inputRoot = $input.path('$'))
{
  "photos": [
#foreach($elem in $inputRoot.photos.photo)
    {
      "id": "$elem.id",
      "photographedBy": "$elem.photographer_first_name $elem.photographer_last_name",
      "title": "$elem.title",
      "ispublic": $elem.ispublic,
      "isfriend": $elem.isfriend,
      "isfamily": $elem.isfamily
    }#if($foreach.hasNext),#end
		
#end
  ]
}
```

다음 예제는 변환의 출력 데이터입니다.

```
{
  "photos": [
    {
      "id": "12345678901",
      "photographedBy": "Saanvi Sarkar",
      "title": "Sample photo 1",
      "ispublic": true,
      "isfriend": false,
      "isfamily": false
    },		
    {
      "id": "23456789012",
      "photographedBy": "Richard Roe",
      "title": "Sample photo 2",
      "ispublic": true,
      "isfriend": false,
      "isfamily": false
    }		
  ]
}
```

이 데이터는 통합 요청으로 전송된 다음, 통합 엔드포인트로 전송됩니다.

## 통합 응답 및 메서드 응답
<a name="photos-example-response"></a>

다음은 통합 엔드포인트의 사진 데이터에 대한 예제 출력 모델입니다. API에 유형이 엄격하게 지정된 SDK를 생성할 때 필수인 메서드 응답 모델에 이 모델을 사용할 수 있습니다. 이를 통해 출력은 Java 또는 Objective-C의 적절한 클래스에 캐스팅됩니다.

```
{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "PhotosOutputModel",
  "type": "object",
  "properties": {
    "photos": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "id": { "type": "string" },
          "photographedBy": { "type": "string" },
          "title": { "type": "string" },
          "ispublic": { "type": "boolean" },
          "isfriend": { "type": "boolean" },
          "isfamily": { "type": "boolean" }
        }
      }
    }
  }
}
```

통합 엔드포인트는 이 모델의 데이터 구조를 준수하는 응답으로 응답을 반환하지 않을 수 있습니다. 예를 들어 통합 응답은 다음과 같을 수 있습니다.

```
  "photos": [
    {
      "id": "12345678901",
      "photographedBy": "Saanvi Sarkar",
      "title": "Sample photo 1",
      "description": "My sample photo 1",
      "public": true,
      "friend": false,
      "family": false
    },		
    {
      "id": "23456789012",
      "photographedBy": "Richard Roe",
      "title": "Sample photo 2",
      "description": "My sample photo 1",
      "public": true,
      "friend": false,
      "family": false
    }		
  ]
}
```

다음 예제 매핑 템플릿은 통합 응답 데이터를 메서드 응답에서 기대하는 형식으로 변환합니다.

```
#set($inputRoot = $input.path('$'))
{
  "photos": [
#foreach($elem in $inputRoot.photos.photo)
    {
      "id": "$elem.id",
      "photographedBy": "$elem.photographer_first_name $elem.photographer_last_name",
      "title": "$elem.title",
      "ispublic": $elem.public,
      "isfriend": $elem.friend,
      "isfamily": $elem.family
    }#if($foreach.hasNext),#end
		
#end
  ]
}
```

다음 예제는 변환의 출력 데이터입니다.

```
{
  "photos": [
    {
      "id": "12345678901",
      "photographedBy": "Saanvi Sarkar",
      "title": "Sample photo 1",
      "ispublic": true,
      "isfriend": false,
      "isfamily": false
    },		
    {
      "id": "23456789012",
      "photographedBy": "Richard Roe",
      "title": "Sample photo 2",
      "ispublic": true,
      "isfriend": false,
      "isfamily": false
    }		
  ]
}
```

이 데이터는 메서드 응답으로 전송된 다음 클라이언트로 다시 전송됩니다.

# API Gateway에서 REST API에 대한 API 요청, 응답 파라미터, 상태 코드 재정의
<a name="apigateway-override-request-response-parameters"></a>

매핑 템플릿 변환을 사용하여 모든 유형의 요청 파라미터, 응답 헤더 또는 응답 상태 코드를 재정의할 수 있습니다. 매핑 템플릿을 사용하려면 다음과 같이 합니다.
+ 다대일 파라미터 매핑 수행
+ 표준 API Gateway 매핑이 적용된 후 파라미터 재정의
+ 본문 내용이나 기타 파라미터 값을 기반으로 파라미터를 조건부로 매핑
+ 프로그래밍 방식으로 새 파라미터 생성
+ 통합 엔드포인트에서 반환한 상태 코드 재정의

재정의는 최종입니다. 각 파라미터에 한 번만 재정의를 적용할 수 있습니다. 같은 파라미터에 여러 번 재정의를 시도하면 API Gateway에서 `5XX` 응답을 반환합니다. 템플릿에서 같은 파라미터를 여러 번 재정의해야 할 경우에는 변수를 하나 생성하여 템플릿 마지막에 재정의를 적용하는 것이 좋습니다. 전체 템플릿을 구문 분석한 후에만 템플릿이 적용됩니다.

## 예제 1: 통합 본문을 기반으로 상태 코드 재정의
<a name="apigateway-override-request-response-examples"></a>

다음 예제에서는 [예제 API](api-gateway-create-api-from-example.md)를 사용하여 통합 응답 본문을 기반으로 상태 코드를 재정의합니다.

------
#### [ AWS Management Console ]

**통합 응답 본문을 기반으로 상태 코드 재정의**

1. [https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)에서 API Gateway 콘솔에 로그인합니다.

1. **API 생성**을 선택합니다.

1. **REST API**에서 **빌드**를 선택합니다.

1. **API 세부 정보**에서 **예제 API**를 선택합니다.

1. **API 생성**을 선택합니다.

   API Gateway는 예제 반려동물 저장소 API를 만듭니다. 반려동물에 대한 정보를 검색하려면 `GET /pets/{petId}`의 API 메서드 요청을 사용합니다. 여기서 `{petId}`는 반려동물의 ID 번호에 해당하는 경로 파라미터입니다.

   이 예제에서는 오류 조건을 탐지했을 때 `GET` 메서드의 응답 코드를 `400`으로 재정의합니다.

1. **리소스** 트리에서, `/{petId}` 아래의 `GET` 메서드를 선택합니다.

1. 먼저 API의 현재 구현을 테스트합니다.

   **테스트** 탭을 선택합니다. 탭을 표시하려면 오른쪽 화살표 버튼을 선택해야 할 수도 있습니다.

1. **petId**에 **-1**을 입력한 다음 **테스트**를 선택합니다.

   **응답 본문**은 범위를 벗어난 오류를 가리킵니다.

   ```
   {
     "errors": [
       {
         "key": "GetPetRequest.petId",
         "message": "The value is out of range."
       }
     ]
   }
   ```

   또한 **로그** 아래의 마지막 줄은 `Method completed with status: 200`으로 끝납니다.

   통합이 성공적으로 완료되었지만 오류가 발생했습니다. 이제 통합 응답을 기반으로 상태 코드를 재정의합니다.

1. **통합 응답** 탭의 **기본값 - 응답**에서 **편집**을 선택합니다.

1. **매핑 템플릿**을 선택합니다.

1. **매핑 템플릿 추가(Add mapping template)**를 선택합니다.

1. **콘텐츠 유형**에 **application/json**을 입력합니다.

1. **템플릿 본문**에 다음을 입력합니다.

   ```
   #set($inputRoot = $input.path('$'))
   $input.json("$")
   #if($inputRoot.toString().contains("error"))
   #set($context.responseOverride.status = 400)
   #end
   ```

   이 매핑 템플릿은 통합 응답에 `error` 문자열이 포함된 경우 `$context.responseOverride.status` 변수를 사용하여 상태 코드를 로 `400`으로 재정의합니다.

1. **저장**을 선택합니다.

1. **테스트** 탭을 선택합니다.

1. **petId**에 **-1**을 입력합니다.

1. 결과에서 **응답 본문(Response Body)**은 범위 밖 오류를 가리킵니다.

   ```
   {
     "errors": [
       {
         "key": "GetPetRequest.petId",
         "message": "The value is out of range."
       }
     ]
   }
   ```

   그러나 **로그** 아래의 마지막 줄은 이제 `Method completed with status: 400`으로 끝납니다.

------
#### [ CloudFormation ]

 이 예제에서는 [본문](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-body) 속성을 사용하여 OpenAPI 정의 파일을 API Gateway로 가져옵니다.

```
AWSTemplateFormatVersion: 2010-09-09
Resources:
  Api:
    Type: 'AWS::ApiGateway::RestApi'
    Properties:
      Body: 
        openapi: 3.0.1
        info:
          title: PetStore Example 1
          description: Example pet store API.
          version: "2025-01-14T00:13:18Z"
        paths:
          /pets/{petId}:
            get:
              parameters:
                - name: petId
                  in: path
                  required: true
                  schema:
                    type: string
              responses:
                "200":
                  description: 200 response
              x-amazon-apigateway-integration:
                httpMethod: GET
                uri: http://petstore.execute-api.us-east-1.amazonaws.com/petstore/pets/{petId}
                responses:
                  default:
                    statusCode: "200"
                    responseTemplates:
                      application/json: |-
                        #set($inputRoot = $input.path('$'))
                        $input.json("$")
                        #if($inputRoot.toString().contains("error"))
                        #set($context.responseOverride.status = 400)
                        #end
                requestParameters:
                  integration.request.path.petId: method.request.path.petId
                passthroughBehavior: when_no_match
                type: http
        components:
          schemas:
            Pet:
              type: object
              properties:
                id:
                  type: integer
                type:
                  type: string
                price:
                  type: number
  ApiGatewayDeployment:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn: Api 
    Properties: 
      RestApiId: !Ref Api
  ApiGatewayDeployment20250219:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn: Api 
    Properties: 
      RestApiId: !Ref Api
  Stage:
    Type: 'AWS::ApiGateway::Stage'
    Properties:
       DeploymentId: !Ref ApiGatewayDeployment20250219
       RestApiId: !Ref Api
       StageName: prod
```

------
#### [ OpenAPI ]

다음 OpenAPI 정의는 `GET pets/{petId}` 리소스를 만들고 통합 본문을 기반으로 상태 코드를 재정의합니다.

```
{
  "openapi" : "3.0.1",
  "info" : {
    "title" : "PetStore Example 1",
    "description" : "Example pet store API.",
    "version" : "2025-01-14T00:13:18Z"
  },
  "paths" : {
    "/pets/{petId}" : {
      "get" : {
        "parameters" : [ {
          "name" : "petId",
          "in" : "path",
          "required" : true,
          "schema" : {
            "type" : "string"
          }
        } ],
        "responses" : {
          "200" : {
            "description" : "200 response"
          }
        },
        "x-amazon-apigateway-integration" : {
          "httpMethod" : "GET",
          "uri" : "http://petstore.execute-api.us-east-1.amazonaws.com/petstore/pets/{petId}",
          "responses" : {
            "default" : {
              "statusCode" : "200",
              "responseTemplates" : {
                "application/json" : "#set($inputRoot = $input.path('$'))\n$input.json(\"$\")\n#if($inputRoot.toString().contains(\"error\"))\n#set($context.responseOverride.status = 400)\n#end"
              }
            }
          },
          "requestParameters" : {
            "integration.request.path.petId" : "method.request.path.petId"
          },
          "passthroughBehavior" : "when_no_match",
          "type" : "http"
        }
      }
    }
  },
  "components" : {
    "schemas" : {
      "Pet" : {
        "type" : "object",
        "properties" : {
          "id" : {
            "type" : "integer"
          },
          "type" : {
            "type" : "string"
          },
          "price" : {
            "type" : "number"
          }
        }
      }
    }
  }
}
```

------

## 예제 2: 요청 헤더 재정의 및 새 헤더 만들기
<a name="apigateway-override-request-response-examples-2"></a>

다음 예제에서는 [예제 API](api-gateway-create-api-from-example.md)를 사용하여 요청 헤더를 재정의하고 새 헤더를 만듭니다.

------
#### [ AWS Management Console ]

**새 헤더를 만들어 메서드의 요청 헤더 재정의**

1. [https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)에서 API Gateway 콘솔에 로그인합니다.

1. 이전 자습서에서 만든 예제 API를 선택합니다. API의 이름은 **PetStore**여야 합니다.

1. **리소스** 트리에서, `/pet` 아래의 `GET` 메서드를 선택합니다.

1. **메서드 요청** 탭의 **메서드 요청 설정**에서 **편집**을 선택합니다.

1. **HTTP 요청 헤더**를 선택한 다음, **헤더 추가**를 선택합니다.

1. **이름**에 **header1**를 입력합니다.

1. **헤더 추가**를 선택한 다음 **header2**라는 두 번째 헤더를 생성합니다.

1. **저장**을 선택합니다.

   이제 매핑 템플릿을 사용하여 이러한 헤더를 하나의 헤더 값으로 결합합니다.

1. **통합 요청** 탭의 **통합 요청 설정**에서 **편집**을 선택합니다.

1. **요청 본문 패스스루**에서 **정의된 템플릿이 없는 경우(권장)**를 선택합니다.

1. **매핑 템플릿**을 선택한 후 다음을 수행합니다.

   1. **매핑 템플릿 추가(Add mapping template)**를 선택합니다.

   1. **콘텐츠 유형**에 **application/json**을 입력합니다.

   1. **템플릿 본문**에 다음을 입력합니다.

      ```
      #set($header1Override = "pets")
      #set($header3Value = "$input.params('header1')$input.params('header2')")
      $input.json("$")
      #set($context.requestOverride.header.header3 = $header3Value)
      #set($context.requestOverride.header.header1 = $header1Override)
      #set($context.requestOverride.header.multivalueheader=[$header1Override, $header3Value])
      ```

      이 매핑 템플릿은 `pets` 문자열로 `header1`을 재정의하고 `header1` 및 `header2`를 결합하는 `$header3Value`라는 다중 값 헤더를 만듭니다.

1. **저장**을 선택합니다.

1. **테스트** 탭을 선택합니다.

1. **헤더**에서 다음 코드를 복사합니다.

   ```
   header1:header1Val
   header2:header2Val
   ```

1. **테스트**를 선택합니다.

   **로그**에 다음 텍스트가 포함된 항목이 보입니다.

   ```
   Endpoint request headers: {header3=header1Valheader2Val, 
   header2=header2Val, header1=pets, x-amzn-apigateway-api-id=api-id,
   Accept=application/json, multivalueheader=pets,header1Valheader2Val}
   ```

------
#### [ CloudFormation ]

 이 예제에서는 [본문](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-body) 속성을 사용하여 OpenAPI 정의 파일을 API Gateway로 가져옵니다.

```
AWSTemplateFormatVersion: 2010-09-09
Resources:
  Api:
    Type: 'AWS::ApiGateway::RestApi'
    Properties:
      Body: 
        openapi: 3.0.1
        info:
          title: PetStore Example 2
          description: Example pet store API.
          version: "2025-01-14T00:36:18Z"
        paths:
          /pets:
            get:
              parameters:
                - name: header2
                  in: header
                  schema:
                    type: string
                - name: page
                  in: query
                  schema:
                    type: string
                - name: type
                  in: query
                  schema:
                    type: string
                - name: header1
                  in: header
                  schema:
                    type: string
              responses:
                "200":
                  description: 200 response
              x-amazon-apigateway-integration:
                httpMethod: GET
                uri: http://petstore.execute-api.us-east-1.amazonaws.com/petstore/pets
                responses:
                  default:
                    statusCode: "200"
                requestParameters:
                  integration.request.header.header1: method.request.header.header1
                  integration.request.header.header2: method.request.header.header2
                  integration.request.querystring.page: method.request.querystring.page
                  integration.request.querystring.type: method.request.querystring.type
                requestTemplates:
                  application/json: |-
                    #set($header1Override = "pets")
                    #set($header3Value = "$input.params('header1')$input.params('header2')")
                    $input.json("$")
                    #set($context.requestOverride.header.header3 = $header3Value)
                    #set($context.requestOverride.header.header1 = $header1Override)
                    #set($context.requestOverride.header.multivalueheader=[$header1Override, $header3Value])
                passthroughBehavior: when_no_match
                type: http
        components:
          schemas:
            Pet:
              type: object
              properties:
                id:
                  type: integer
                type:
                  type: string
                price:
                  type: number
  ApiGatewayDeployment:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn: Api 
    Properties: 
      RestApiId: !Ref Api
  ApiGatewayDeployment20250219:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn: Api 
    Properties: 
      RestApiId: !Ref Api
  Stage:
    Type: 'AWS::ApiGateway::Stage'
    Properties:
       DeploymentId: !Ref ApiGatewayDeployment20250219
       RestApiId: !Ref Api
       StageName: prod
```

------
#### [ OpenAPI ]

 다음 OpenAPI 정의는 `GET pets` 리소스를 만들고 요청 헤더를 재정의하고 새 헤더를 만듭니다.

```
{
  "openapi" : "3.0.1",
  "info" : {
    "title" : "PetStore Example 2",
    "description" : "Example pet store API.",
    "version" : "2025-01-14T00:36:18Z"
  },
  "paths" : {
    "/pets" : {
      "get" : {
        "parameters" : [ {
          "name" : "header2",
          "in" : "header",
          "schema" : {
            "type" : "string"
          }
        }, {
          "name" : "page",
          "in" : "query",
          "schema" : {
            "type" : "string"
          }
        }, {
          "name" : "type",
          "in" : "query",
          "schema" : {
            "type" : "string"
          }
        }, {
          "name" : "header1",
          "in" : "header",
          "schema" : {
            "type" : "string"
          }
        } ],
        "responses" : {
          "200" : {
            "description" : "200 response"
          }
        },
        "x-amazon-apigateway-integration" : {
          "httpMethod" : "GET",
          "uri" : "http://petstore.execute-api.us-east-1.amazonaws.com/petstore/pets",
          "responses" : {
            "default" : {
              "statusCode" : "200"
            }
          },
          "requestParameters" : {
            "integration.request.header.header1" : "method.request.header.header1",
            "integration.request.header.header2" : "method.request.header.header2",
            "integration.request.querystring.page" : "method.request.querystring.page",
            "integration.request.querystring.type" : "method.request.querystring.type"
          },
          "requestTemplates" : {
            "application/json" : "#set($header1Override = \"pets\")\n#set($header3Value = \"$input.params('header1')$input.params('header2')\")\n$input.json(\"$\")\n#set($context.requestOverride.header.header3 = $header3Value)\n#set($context.requestOverride.header.header1 = $header1Override)\n#set($context.requestOverride.header.multivalueheader=[$header1Override, $header3Value])"
          },
          "passthroughBehavior" : "when_no_match",
          "type" : "http"
        }
      }
    }
  }
}
```

------

매핑 템플릿 재정의를 사용하려면 다음 `$context` 변수 중 하나 이상을 추가합니다. `$context` 변수 목록은 [데이터 변환용 컨텍스트 변수](api-gateway-mapping-template-reference.md#context-variable-reference) 섹션을 참조하시기 바랍니다.

# 자습서: AWS 서비스에 대한 통합의 통합 요청 및 응답 수정
<a name="set-up-data-transformations-in-api-gateway"></a>

다음 자습서에서는 콘솔과 AWS CLI를 사용하여 통합 요청 및 응답을 변환하도록 매핑 템플릿을 설정하기 위해 매핑 템플릿 변환을 사용하는 방법을 보여줍니다.

**Topics**
+ [API Gateway 콘솔을 사용하여 데이터 변환 설정](#mapping-example-console)
+ [AWS CLI를 사용하여 데이터 변환 설정](#mapping-example-cli)
+ [완성된 데이터 변환 CloudFormation 템플릿](#api-gateway-data-transformations-full-cfn-stack)

## API Gateway 콘솔을 사용하여 데이터 변환 설정
<a name="mapping-example-console"></a>

이 자습서에서는 .zip 파일([data-transformation-tutorial-console.zip](samples/data-transformation-tutorial-console.zip))을 사용하여 불완전한 API 및 DynamoDB 테이블을 생성합니다. 이 불완전한 API에는 `GET` 및 `POST` 메서드가 포함된 `/pets` 리소스가 있습니다.
+ `GET` 메서드는 `http://petstore-demo-endpoint.execute-api.com/petstore/pets` HTTP 엔드포인트에서 데이터를 가져옵니다. 출력 데이터는 [API Gateway에서 REST API의 데이터 변환 매핑](models-mappings.md)의 매핑 템플릿에 따라 변환됩니다.
+ `POST` 메서드를 사용하면 사용자가 매핑 템플릿을 사용하여 Amazon DynamoDB 테이블에 `POST` 반려동물 정보를 입력할 수 있습니다.

[CloudFormation용 앱 생성 템플릿](samples/data-transformation-tutorial-console.zip)을 다운로드하고 압축을 해제합니다. 이 템플릿을 사용하여 반려동물 정보와 불완전한 API를 게시하기 위한 DynamoDB 테이블을 생성할 것입니다. API Gateway 콘솔에서 나머지 단계를 완료하게 됩니다.

**CloudFormation 스택을 생성하려면**

1. CloudFormation 콘솔([https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/))을 엽니다.

1. **스택 생성**을 선택한 다음 **새 리소스 사용(표준)**을 선택합니다.

1. **템플릿 지정**에서 **템플릿 파일 업로드**를 선택합니다.

1. 다운로드한 템플릿을 선택합니다.

1. **다음**을 선택합니다.

1. **스택 이름**에 **data-transformation-tutorial-console**을 입력하고 **다음**을 선택합니다.

1. **스택 옵션 구성**에서 **다음**을 선택합니다.

1. **기능**의 경우 CloudFormation이 계정에 IAM 리소스를 생성할 수 있음을 확인합니다.

1. **다음**을 선택한 후 **제출**을 선택합니다.

CloudFormation은 템플릿에 지정된 리소스를 프로비저닝합니다. 리소스 프로비저닝을 완료하는 데 몇 분 정도 걸릴 수 있습니다. CloudFormation 스택 상태가 **CREATE\$1COMPLETE**인 경우 다음 단계로 넘어갈 준비가 된 것입니다.

**`GET` 통합 응답을 테스트하는 방법**

1. **data-transformation-tutorial-console**의 CloudFormation 스택에 있는 **리소스** 탭에서 API의 물리적 ID를 선택합니다.

1. 기본 탐색 창에서 **리소스**를 선택하고 **GET** 메서드를 선택합니다.

1. **테스트** 탭을 선택합니다. 탭을 표시하려면 오른쪽 화살표 버튼을 선택해야 할 수도 있습니다.

   테스트 결과는 다음과 같습니다.

   ```
   [
     {
       "id": 1,
       "type": "dog",
       "price": 249.99
     },
     {
       "id": 2,
       "type": "cat",
       "price": 124.99
     },
     {
       "id": 3,
       "type": "fish",
       "price": 0.99
     }
   ]
   ```

   [API Gateway에서 REST API의 데이터 변환 매핑](models-mappings.md)의 매핑 테이블에 따라 이 출력 데이터를 변환합니다.

**`GET` 통합 응답을 변환하는 방법**

1. **통합 응답** 탭을 선택합니다.

   현재 정의된 매핑 템플릿이 없으므로 통합 응답은 변환되지 않습니다.

1. **기본값 - 응답**에서 **편집**을 선택합니다.

1. **매핑 템플릿**을 선택한 후 다음을 수행합니다.

   1. **매핑 템플릿 추가(Add mapping template)**를 선택합니다.

   1. **콘텐츠 유형**에 **application/json**을 입력합니다.

   1. **템플릿 본문**에 다음을 입력합니다.

      ```
      #set($inputRoot = $input.path('$'))
      [
      #foreach($elem in $inputRoot)
        {
          "description" : "Item $elem.id is a $elem.type.",
          "askingPrice" : $elem.price
        }#if($foreach.hasNext),#end
      
      #end
      ]
      ```

   **저장**을 선택합니다.

**`GET` 통합 응답을 테스트하는 방법**
+ **테스트** 탭을 선택한 다음 **테스트**를 선택합니다.

  테스트 출력에는 변환된 응답이 표시됩니다.

  ```
  [
    {
      "description" : "Item 1 is a dog.",
      "askingPrice" : 249.99
    },
    {
      "description" : "Item 2 is a cat.",
      "askingPrice" : 124.99
    },
    {
      "description" : "Item 3 is a fish.",
      "askingPrice" : 0.99
    }
  ]
  ```

**`POST` 메서드의 입력 데이터를 변환하는 방법**

1. **POST** 메서드를 선택합니다.

1. **통합 요청** 탭을 선택한 다음 **통합 요청 설정**에서 **편집**을 선택합니다.

   CloudFormation 템플릿에 일부 통합 요청 필드가 채워져 있습니다.
   +  통합 유형은 AWS 서비스입니다.
   +  AWS 서비스는 DynamoDB입니다.
   +  HTTP 메서드는 `POST`입니다.
   +  작업은 `PutItem`입니다.
   +  API Gateway가 DynamoDB 테이블에 항목을 넣을 수 있도록 하는 실행 역할은 `data-transformation-tutorial-console-APIGatewayRole`입니다. API Gateway가 DynamoDB와 상호 작용하는 데 필요한 최소한의 권한을 가질 수 있도록 하기 위해 CloudFormation이 생성한 역할입니다.

    DynamoDB 테이블의 이름이 지정되지 않았습니다. 다음 단계에서 이름을 지정합니다.

1. **요청 본문 패스스루**에서 **없음**을 선택합니다.

   이렇게 하면 API는 매핑 템플릿이 없는 Content-Types의 데이터를 거부합니다.

1. **매핑 템플릿**을 선택합니다.

1. **콘텐츠 유형**이 `application/json`으로 설정되어 있습니다. 이는 application/json이 아닌 콘텐츠 유형은 API에서 거부함을 의미합니다. 통합 패스스루 동작에 관한 자세한 정보는 [API Gateway의 REST API에 대한 매핑 템플릿이 없는 페이로드의 메서드 요청 동작](integration-passthrough-behaviors.md) 섹션을 참조하세요.

1. 텍스트 편집기에 다음 코드를 입력합니다.

   ```
   {
       "TableName":"data-transformation-tutorial-console-ddb",
       "Item": {
           "id": {
               "N": $input.json("$.id")
           },
           "type": {
               "S": $input.json("$.type")
           },
           "price": {
               "N": $input.json("$.price")
           }
       }
   }
   ```

    이 템플릿은 테이블을 `data-transformation-tutorial-console-ddb`로 지정하고 항목을 `id`, `type` 및 `price`로 설정합니다. 항목은 `POST` 메서드 본문에서 가져옵니다. 또한 매핑 템플릿을 만드는 데 데이터 모델을 사용할 수 있습니다. 자세한 내용은 [API Gateway의 REST API API 검증 요청](api-gateway-method-request-validation.md) 섹션을 참조하세요.

1. **저장**을 선택하여 매핑 템플릿을 저장합니다.

**메서드 및 `POST` 메서드의 통합 응답을 추가하는 방법**

CloudFormation이 빈 메서드와 통합 응답을 만들었습니다. 이 응답을 편집하여 자세한 정보를 제공할 수 있습니다. 응답을 편집하는 방법에 대한 자세한 내용은 [API Gateway의 REST API에 대한 파라미터 매핑 예제](request-response-data-mappings.md) 섹션을 참조하세요.

1. **통합 응답** 탭의 **기본값 - 응답**에서 **편집**을 선택합니다.

1. **매핑 템플릿**을 선택한 다음 **매핑 템플릿 추가**를 선택합니다.

1. **Content-type**에 **application/json**을 입력합니다.

1. 코드 편집기에서 다음 출력 매핑 템플릿을 입력하여 출력 메시지를 보냅니다.

   ```
   { "message" : "Your response was recorded at $context.requestTime" }
   ```

   컨텍스트 변수에 대한 자세한 내용은 [데이터 변환용 컨텍스트 변수](api-gateway-mapping-template-reference.md#context-variable-reference) 섹션을 참조하세요.

1. **저장**을 선택하여 매핑 템플릿을 저장합니다.

**`POST` 메서드 테스트**

**테스트** 탭을 선택합니다. 탭을 표시하려면 오른쪽 화살표 버튼을 선택해야 할 수도 있습니다.

1. 요청 본문에 다음 예를 입력합니다.

   ```
   {
             "id": "4",
             "type" : "dog",
             "price": "321"
   }
   ```

1. **테스트**를 선택합니다.

   출력에 성공 메시지가 표시되어야 합니다.

    [https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/)에서 DynamoDB 콘솔을 열어 예시 항목이 테이블에 있는지 확인할 수 있습니다.

**CloudFormation 스택을 삭제하려면**

1. CloudFormation 콘솔([https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/))을 엽니다.

1. CloudFormation 스택을 선택합니다.

1. **삭제**를 선택한 다음 해당 선택을 확인합니다.

## AWS CLI를 사용하여 데이터 변환 설정
<a name="mapping-example-cli"></a>

이 자습서에서는 .zip 파일([data-transformation-tutorial-cli.zip](samples/data-transformation-tutorial-cli.zip))을 사용하여 불완전한 API 및 DynamoDB 테이블을 생성합니다. 이 불완전한 API에는 `http://petstore-demo-endpoint.execute-api.com/petstore/pets` HTTP 엔드포인트와 통합된 `GET` 메서드가 포함된 `/pets` 리소스가 있습니다. DynamoDB 테이블에 연결할 `POST` 메서드를 생성하고 매핑 템플릿을 사용하여 DynamoDB 테이블에 데이터를 입력합니다.
+ [API Gateway에서 REST API의 데이터 변환 매핑](models-mappings.md)의 매핑 템플릿에 따라 출력 데이터를 변화합니다.
+ 사용자가 매핑 템플릿을 사용하여 Amazon DynamoDB 테이블에 `POST` 반려동물 정보를 입력할 수 있도록 `POST` 메서드를 생성합니다.

**CloudFormation 스택을 생성하려면**

[CloudFormation용 앱 생성 템플릿](samples/data-transformation-tutorial-cli.zip)을 다운로드하고 압축을 해제합니다.

다음 자습서를 완료하려면 [AWS Command Line Interface(AWS CLI) 버전 2](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)가 필요합니다.

긴 명령의 경우 이스케이프 문자(`\`)를 사용하여 명령을 여러 행으로 분할합니다.
**참고**  
Windows에서는 일반적으로 사용하는 일부 Bash CLI 명령(예: `zip`)은 운영 체제의 기본 제공 터미널에서 지원되지 않습니다. Ubuntu와 Bash의 Windows 통합 버전을 가져오려면 [Linux용 Windows Subsystem을 설치](https://learn.microsoft.com/en-us/windows/wsl/install)합니다. 이 안내서의 예제 CLI 명령은 Linux 형식을 사용합니다. Windows CLI를 사용하는 경우 인라인 JSON 문서를 포함하는 명령의 형식을 다시 지정해야 합니다.

1.  다음 명령을 사용하여 CloudFormation 스택을 생성합니다.

   ```
   aws cloudformation create-stack --stack-name data-transformation-tutorial-cli --template-body file://data-transformation-tutorial-cli.zip --capabilities CAPABILITY_NAMED_IAM 
   ```

1. CloudFormation은 템플릿에 지정된 리소스를 프로비저닝합니다. 리소스 프로비저닝을 완료하는 데 몇 분 정도 걸릴 수 있습니다. 다음 명령을 실행하여 CloudFormation 스택의 상태를 확인합니다.

   ```
   aws cloudformation describe-stacks --stack-name data-transformation-tutorial-cli
   ```

1. CloudFormation 스택의 상태가 `StackStatus: "CREATE_COMPLETE"`이면 다음 명령을 사용하여 향후 단계에 대한 관련 출력 값을 검색합니다.

   ```
    aws cloudformation describe-stacks --stack-name data-transformation-tutorial-cli --query "Stacks[*].Outputs[*].{OutputKey: OutputKey, OutputValue: OutputValue, Description: Description}"
   ```

   출력 값은 다음과 같습니다.
   + ApiRole은 API Gateway가 DynamoDB 테이블에 항목을 배치할 수 있도록 하는 역할 이름입니다. 이 자습서에서 역할 이름은 `data-transformation-tutorial-cli-APIGatewayRole-ABCDEFG`입니다.
   + DDBTableName은 DynamoDB 테이블의 이름입니다. 이 자습서에서 테이블 이름은 `data-transformation-tutorial-cli-ddb`입니다.
   + ResourceId는 `GET` 및 `POST` 메서드가 노출되는 반려동물 리소스의 ID입니다. 이 자습서에서 리소스 ID는 `efg456`입니다.
   + APIID는 API의 ID입니다. 이 자습서에서 API ID는 `abc123`입니다.

**데이터 변환 전에 `GET` 메서드를 테스트하는 방법**
+ 다음 명령을 사용하여 `GET` 메서드를 테스트합니다.

  ```
  aws apigateway test-invoke-method --rest-api-id abc123 \
            --resource-id efg456 \
            --http-method GET
  ```

  테스트의 출력은 다음과 같습니다.

  ```
  [
    {
      "id": 1,
      "type": "dog",
      "price": 249.99
    },
    {
      "id": 2,
      "type": "cat",
      "price": 124.99
    },
    {
      "id": 3,
      "type": "fish",
      "price": 0.99
    }
  ]
  ```

  [API Gateway에서 REST API의 데이터 변환 매핑](models-mappings.md)의 매핑 테이블에 따라 이 출력 데이터를 변환합니다.

**`GET` 통합 응답을 변환하는 방법**
+ 다음 명령을 사용하여 `GET` 메서드 통합 응답을 업데이트합니다. *rest-api-id*와 *resource-id*를 실제 값으로 바꿉니다.

  다음 명령을 사용하여 통합 응답을 생성합니다.

  ```
  aws apigateway put-integration-response --rest-api-id abc123 \
    --resource-id efg456 \
    --http-method GET \
    --status-code 200 \
    --selection-pattern "" \
    --response-templates '{"application/json": "#set($inputRoot = $input.path(\"$\"))\n[\n#foreach($elem in $inputRoot)\n {\n  \"description\": \"Item $elem.id is a $elem.type\",\n  \"askingPrice\": \"$elem.price\"\n }#if($foreach.hasNext),#end\n\n#end\n]"}'
  ```

**`GET` 메서드를 테스트하는 방법**
+ 다음 명령을 사용하여 `GET` 메서드를 테스트합니다.

  ```
  aws apigateway test-invoke-method --rest-api-id abc123 \
    --resource-id efg456 \
    --http-method GET \
  ```

  테스트 출력에는 변환된 응답이 표시됩니다.

  ```
  [
    {
      "description" : "Item 1 is a dog.",
      "askingPrice" : 249.99
    },
    {
      "description" : "Item 2 is a cat.",
      "askingPrice" : 124.99
    },
    {
      "description" : "Item 3 is a fish.",
      "askingPrice" : 0.99
    }
  ]
  ```

**`POST` 메서드를 생성하는 방법**

1. 다음 명령을 사용하여 `/pets` 리소스에 새로운 메서드를 생성합니다.

   ```
   aws apigateway put-method --rest-api-id abc123 \
     --resource-id efg456 \
     --http-method POST \
     --authorization-type "NONE" \
   ```

   이 방법을 사용하면 CloudFormation 스택에 생성한 DynamoDB 테이블로 반려동물 정보를 보낼 수 있습니다.

1.  다음 명령을 사용하여 `POST` 메서드에 AWS 서비스 통합을 생성합니다.

   ```
   aws apigateway put-integration --rest-api-id abc123 \
     --resource-id efg456 \
     --http-method POST \
     --type AWS \
     --integration-http-method POST \
     --uri "arn:aws:apigateway:us-east-2:dynamodb:action/PutItem" \
     --credentials arn:aws:iam::111122223333:role/data-transformation-tutorial-cli-APIGatewayRole-ABCDEFG \
     --request-templates '{"application/json":"{\"TableName\":\"data-transformation-tutorial-cli-ddb\",\"Item\":{\"id\":{\"N\":$input.json(\"$.id\")},\"type\":{\"S\":$input.json(\"$.type\")},\"price\":{\"N\":$input.json(\"$.price\")} }}"}'
   ```

1.  다음 명령을 사용하여 성공적인 `POST` 메서드 호출에 대한 메서드 응답을 생성합니다.

   ```
   aws apigateway put-method-response --rest-api-id abc123 \
     --resource-id efg456 \
     --http-method POST \
     --status-code 200
   ```

1. 다음 명령을 사용하여 성공적인 `POST` 메서드 호출에 대한 통합 응답을 생성합니다.

   ```
   aws apigateway put-integration-response --rest-api-id abc123 \
     --resource-id efg456 \
     --http-method POST \
     --status-code 200 \
     --selection-pattern "" \
     --response-templates '{"application/json": "{\"message\": \"Your response was recorded at $context.requestTime\"}"}'
   ```

**`POST` 메서드를 테스트하는 방법**
+ 다음 명령을 사용하여 `POST` 메서드를 테스트합니다.

  ```
  aws apigateway test-invoke-method --rest-api-id abc123 \
    --resource-id efg456 \
    --http-method POST \
    --body '{\"id\": \"4\", \"type\": \"dog\", \"price\": \"321\"}'
  ```

  출력에 성공 메시지가 표시됩니다.

**CloudFormation 스택을 삭제하려면**
+ 다음 명령을 사용하여 CloudFormation 리소스를 삭제합니다.

  ```
  aws cloudformation delete-stack  --stack-name data-transformation-tutorial-cli
  ```

## 완성된 데이터 변환 CloudFormation 템플릿
<a name="api-gateway-data-transformations-full-cfn-stack"></a>

다음 예시는 `GET` 및 `POST` 메서드가 있는 `/pets` 리소스가 포함된 DynamoDB 테이블과 API를 생성하는 완성된 CloudFormation 템플릿입니다.
+ `GET` 메서드는 `http://petstore-demo-endpoint.execute-api.com/petstore/pets` HTTP 엔드포인트에서 데이터를 가져옵니다. 출력 데이터는 [API Gateway에서 REST API의 데이터 변환 매핑](models-mappings.md)의 매핑 템플릿에 따라 변환됩니다.
+ `POST` 메서드를 사용하면 사용자가 매핑 템플릿을 사용하여 DynamoDB 테이블에 `POST` 반려동물 정보를 입력할 수 있습니다.

### 예제 CloudFormation 템플릿
<a name="mapping-template-cfn-example"></a>

```
AWSTemplateFormatVersion: 2010-09-09
Description: A completed Amazon API Gateway REST API that uses non-proxy integration to POST to an Amazon DynamoDB table and non-proxy integration to GET transformed pets data.
Parameters:
  StageName:
    Type: String
    Default: v1
    Description: Name of API stage.
Resources:
  DynamoDBTable:
    Type: 'AWS::DynamoDB::Table'
    Properties:
      TableName: !Sub data-transformation-tutorial-complete
      AttributeDefinitions:
        - AttributeName: id
          AttributeType: N
      KeySchema:
        - AttributeName: id
          KeyType: HASH
      ProvisionedThroughput:
        ReadCapacityUnits: 5
        WriteCapacityUnits: 5
  APIGatewayRole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17		 	 	 
        Statement:
          - Action:
              - 'sts:AssumeRole'
            Effect: Allow
            Principal:
              Service:
                - apigateway.amazonaws.com
      Policies:
        - PolicyName: APIGatewayDynamoDBPolicy
          PolicyDocument:
            Version: 2012-10-17		 	 	 
            Statement:
              - Effect: Allow
                Action:
                  - 'dynamodb:PutItem'
                Resource: !GetAtt DynamoDBTable.Arn
  Api:
    Type: 'AWS::ApiGateway::RestApi'
    Properties:
      Name: data-transformation-complete-api
      ApiKeySourceType: HEADER
  PetsResource:
    Type: 'AWS::ApiGateway::Resource'
    Properties:
      RestApiId: !Ref Api
      ParentId: !GetAtt Api.RootResourceId
      PathPart: 'pets'
  PetsMethodGet:
    Type: 'AWS::ApiGateway::Method'
    Properties:
      RestApiId: !Ref Api
      ResourceId: !Ref PetsResource
      HttpMethod: GET
      ApiKeyRequired: false
      AuthorizationType: NONE
      Integration:
        Type: HTTP
        Credentials: !GetAtt APIGatewayRole.Arn
        IntegrationHttpMethod: GET
        Uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets/
        PassthroughBehavior: WHEN_NO_TEMPLATES
        IntegrationResponses:
          - StatusCode: '200'
            ResponseTemplates:
              application/json: "#set($inputRoot = $input.path(\"$\"))\n[\n#foreach($elem in $inputRoot)\n {\n  \"description\": \"Item $elem.id is a $elem.type\",\n  \"askingPrice\": \"$elem.price\"\n }#if($foreach.hasNext),#end\n\n#end\n]"
      MethodResponses:
        - StatusCode: '200'
  PetsMethodPost:
    Type: 'AWS::ApiGateway::Method'
    Properties:
      RestApiId: !Ref Api
      ResourceId: !Ref PetsResource
      HttpMethod: POST
      ApiKeyRequired: false
      AuthorizationType: NONE
      Integration:
        Type: AWS
        Credentials: !GetAtt APIGatewayRole.Arn
        IntegrationHttpMethod: POST
        Uri: arn:aws:apigateway:us-west-1:dynamodb:action/PutItem
        PassthroughBehavior: NEVER
        RequestTemplates: 
          application/json: "{\"TableName\":\"data-transformation-tutorial-complete\",\"Item\":{\"id\":{\"N\":$input.json(\"$.id\")},\"type\":{\"S\":$input.json(\"$.type\")},\"price\":{\"N\":$input.json(\"$.price\")} }}"
        IntegrationResponses:
          - StatusCode: 200
            ResponseTemplates:
              application/json: "{\"message\": \"Your response was recorded at $context.requestTime\"}"
      MethodResponses:
        - StatusCode: '200'

  ApiDeployment:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn:
      - PetsMethodGet
    Properties:
      RestApiId: !Ref Api
      StageName: !Sub '${StageName}'
Outputs:
  ApiId:
    Description: API ID for CLI commands
    Value: !Ref Api
  ResourceId:
    Description: /pets resource ID for CLI commands
    Value: !Ref PetsResource
  ApiRole:
    Description: Role ID to allow API Gateway to put and scan items in DynamoDB table
    Value: !Ref APIGatewayRole
  DDBTableName:
    Description: DynamoDB table name
    Value: !Ref DynamoDBTable
```

# API Gateway의 템플릿 변환 매핑에 변수를 사용하는 예제
<a name="api-gateway-mapping-variable-examples"></a>

다음 예제는 매핑 템플릿에서 `$context`, `input` 및 `util` 변수를 사용하는 방법을 보여줍니다. 모의 통합 또는 입력 이벤트를 API Gateway에 반환하는 Lambda 비프록시 통합을 사용할 수 있습니다. 데이터 변환에 지원되는 모든 변수 목록은 [API Gateway의 데이터 변환을 위한 변수](api-gateway-mapping-template-reference.md) 섹션을 참조하시기 바랍니다.

## 예제 1: 여러 `$context` 변수를 통합 엔드포인트에 전달
<a name="context-variables-template-example"></a>

다음 예제는 받은 `$context` 변수를, 통합 요청 페이로드에서 약간 다른 이름을 가진 백엔드 변수에 매핑하는 매핑 템플릿을 보여 줍니다.

```
{
    "stage" : "$context.stage",
    "request_id" : "$context.requestId",
    "api_id" : "$context.apiId",
    "resource_path" : "$context.resourcePath",
    "resource_id" : "$context.resourceId",
    "http_method" : "$context.httpMethod",
    "source_ip" : "$context.identity.sourceIp",
    "user-agent" : "$context.identity.userAgent",
    "account_id" : "$context.identity.accountId",
    "api_key" : "$context.identity.apiKey",
    "caller" : "$context.identity.caller",
    "user" : "$context.identity.user",
    "user_arn" : "$context.identity.userArn"
}
```

이 매핑 템플릿의 출력은 다음과 같아야 합니다.

```
{
  stage: 'prod',
  request_id: 'abcdefg-000-000-0000-abcdefg',
  api_id: 'abcd1234',
  resource_path: '/',
  resource_id: 'efg567',
  http_method: 'GET',
  source_ip: '192.0.2.1',
  user-agent: 'curl/7.84.0',
  account_id: '111122223333',
  api_key: 'MyTestKey',
  caller: 'ABCD-0000-12345',
  user: 'ABCD-0000-12345',
  user_arn: 'arn:aws:sts::111122223333:assumed-role/Admin/carlos-salazar'
}
```

이러한 변수 중 하나가 API 키입니다. 이 예제는 메서드에 API 키가 필요하다는 것을 전제로 합니다.

## 예제 2: 모든 요청 파라미터를 JSON 페이로드를 통해 통합 엔드포인트로 전달
<a name="input-examples-mapping-templates"></a>

다음 예제에서는 `path`, `querystring` 및 `header` 파라미터를 포함한 모든 요청 파라미터를 JSON 페이로드를 통해 통합 엔드포인트로 전달합니다.

```
#set($allParams = $input.params())
{
  "params" : {
    #foreach($type in $allParams.keySet())
    #set($params = $allParams.get($type))
    "$type" : {
      #foreach($paramName in $params.keySet())
      "$paramName" : "$util.escapeJavaScript($params.get($paramName))"
      #if($foreach.hasNext),#end
      #end
    }
    #if($foreach.hasNext),#end
    #end
  }
}
```

요청에 다음 입력 파라미터가 있는 경우:
+ `myparam`이라는 경로 매개변수
+ 쿼리 문자열 파라미터 `querystring1=value1,value2`
+ `"header1" : "value1"` 헤더입니다.

이 매핑 템플릿의 출력은 다음과 같아야 합니다.

```
{"params":{"path":{"example2":"myparamm"},"querystring":{"querystring1":"value1,value2"},"header":{"header1":"value1"}}}
```

## 예제 3: 메서드 요청의 하위 섹션을 통합 엔드포인트에 전달
<a name="input-example-json-mapping-template"></a>

 다음 예제에서는 `name` 입력 파라미터를 사용하여 `name` 파라미터만 검색하고 `input.json('$')` 입력 파라미터를 사용하여 메서드 요청의 전체 본문을 검색합니다.

```
{
    "name" : "$input.params('name')",
    "body" : $input.json('$') 
}
```

쿼리 문자열 `name=Bella&type=dog` 파라미터와 다음 본문이 포함된 요청의 경우:

```
{
    "Price" : "249.99",
    "Age": "6"
}
```

이 매핑 템플릿의 출력은 다음과 같아야 합니다.

```
{
    "name" : "Bella",
    "body" : {"Price":"249.99","Age":"6"}
}
```

이 매핑 템플릿은 `type=dog` 쿼리 문자열 파라미터를 제거합니다.

 JSON 입력에 이스케이프 처리되지 않은 문자가 포함되어 있고 이 문자가 자바스크립트로 구문 분석할 수 없는 경우 API 게이트웨이에서 400 응답을 반환할 수 있습니다. `$util.escapeJavaScript($input.json('$'))`을 적용하면 JSON 입력을 올바르게 구문 분석할 수 있습니다.

`$util.escapeJavaScript($input.json('$'))`이 적용된 이전 예는 다음과 같습니다.

```
{
    "name" : "$input.params('name')",
    "body" : "$util.escapeJavaScript($input.json('$'))"
}
```

이 경우 이 매핑 템플릿의 출력은 다음과 같아야 합니다.

```
{
    "name" : "Bella",
    "body": {"Price":"249.99","Age":"6"}
}
```

## 예제 4: JSONPath 표현식을 사용하여 메서드 요청의 하위 섹션을 통합 엔드포인트에 전달
<a name="input-example-inputs-mapping-template"></a>

다음 예제에서는 JSONPath 표현식을 사용하여 요청 본문에서 `name` 입력 파라미터와 `Age`만 검색합니다.

```
{
    "name" : "$input.params('name')",
    "body" : $input.json('$.Age')  
}
```

쿼리 문자열 `name=Bella&type=dog` 파라미터와 다음 본문이 포함된 요청의 경우:

```
{
    "Price" : "249.99",
    "Age": "6"
}
```

이 매핑 템플릿의 출력은 다음과 같아야 합니다.

```
{
    "name" : "Bella",
    "body" : "6"
}
```

이 매핑 템플릿은 본문에서 `type=dog` 쿼리 문자열 파라미터와 `Price` 필드를 제거합니다.

 메서드 요청 페이로드에 이스케이프 처리되지 않은 문자가 포함되어 있고 이 문자가 자바스크립트로 구문 분석할 수 없는 경우 API Gateway에서 `400` 응답을 반환할 수 있습니다. `$util.escapeJavaScript()`을 적용하면 JSON 입력을 올바르게 구문 분석할 수 있습니다.

`$util.escapeJavaScript($input.json('$.Age'))`이 적용된 이전 예는 다음과 같습니다.

```
{
    "name" : "$input.params('name')",
    "body" : "$util.escapeJavaScript($input.json('$.Age'))" 
}
```

이 경우 이 매핑 템플릿의 출력은 다음과 같아야 합니다.

```
{
    "name" : "Bella",
    "body": "\"6\""
}
```

## 예제 5: JSONPath 표현식을 사용하여 메서드 요청에 대한 정보를 통합 엔드포인트에 전달
<a name="input-example-request-and-response"></a>

다음 예제에서는 `$input.params()`, `$input.path()` 및 `$input.json()`을 사용하여 메서드 요청에 대한 정보를 통합 엔드포인트로 전송합니다. 이 매핑 템플릿은 `size()` 메서드를 사용하여 목록의 요소 수를 제공합니다.

```
{
    "id" : "$input.params('id')",
    "count" : "$input.path('$.things').size()",
    "things" : $input.json('$.things')
}
```

경로 `123` 매개변수와 다음 본문이 포함된 요청의 경우:

```
{
      "things": {
            "1": {},
            "2": {},
            "3": {}
      }
}
```

이 매핑 템플릿의 출력은 다음과 같아야 합니다.

```
{"id":"123","count":"3","things":{"1":{},"2":{},"3":{}}}
```

 메서드 요청 페이로드에 이스케이프 처리되지 않은 문자가 포함되어 있고 이 문자가 자바스크립트로 구문 분석할 수 없는 경우 API Gateway에서 `400` 응답을 반환할 수 있습니다. `$util.escapeJavaScript()`을 적용하면 JSON 입력을 올바르게 구문 분석할 수 있습니다.

`$util.escapeJavaScript($input.json('$.things'))`이 적용된 이전 예는 다음과 같습니다.

```
{
     "id" : "$input.params('id')",
     "count" : "$input.path('$.things').size()",
     "things" : "$util.escapeJavaScript($input.json('$.things'))"
}
```

이 매핑 템플릿의 출력은 다음과 같아야 합니다.

```
{"id":"123","count":"3","things":"{\"1\":{},\"2\":{},\"3\":{}}"}
```

# API Gateway의 데이터 변환을 위한 변수
<a name="api-gateway-mapping-template-reference"></a>

파라미터 매핑을 만들 때 컨텍스트 변수를 데이터 소스로 사용할 수 있습니다. 매핑 템플릿 변환을 만들 때 [Velocity Template Language(VTL)](https://velocity.apache.org/engine/devel/vtl-reference.html)로 작성하는 스크립트에서 컨텍스트 변수, 입력 및 유틸리티 변수를 사용할 수 있습니다. 이러한 참조 변수를 사용하는 예제 매핑 템플릿을 알아보려면 [API Gateway의 템플릿 변환 매핑에 변수를 사용하는 예제](api-gateway-mapping-variable-examples.md) 섹션을 참조하시기 바랍니다.

액세스 로깅을 위한 참조 변수 목록을 알아보려면 [API Gateway에 대한 액세스 로깅 변수](api-gateway-variables-for-access-logging.md) 섹션을 참조하시기 바랍니다.

## 데이터 변환용 컨텍스트 변수
<a name="context-variable-reference"></a>

데이터 변환에 다음 대소문자 구분 `$context` 변수를 사용할 수 있습니다.


| 파라미터 | 설명 | 
| --- | --- | 
| \$1context.accountId |  API 소유자의 AWS 계정 ID입니다.  | 
| \$1context.apiId |  식별자 API Gateway가 API에 할당합니다.  | 
| \$1context.authorizer.claims.property |  메서드 호출자가 성공적으로 인증된 후 Amazon Cognito 사용자 풀에서 반환된 클레임의 속성입니다. 자세한 내용은 [Amazon Cognito 사용자 풀을 권한 부여자로 사용하여 REST API에 대한 액세스 제어](apigateway-integrate-with-cognito.md) 단원을 참조하세요.  `$context.authorizer.claims`를 호출하면 null이 반환됩니다.   | 
| \$1context.authorizer.principalId |  클라이언트가 전송한 토큰과 연결되고 API Gateway Lambda 권한 부여자(이전에는 사용자 지정 권한 부여자라고 함)에서 반환한 보안 주체 사용자 식별입니다. 자세한 내용은 [API Gateway Lambda 권한 부여자 사용](apigateway-use-lambda-authorizer.md) 단원을 참조하세요.  | 
| \$1context.authorizer.property |  API Gateway Lambda 권한 부여자 함수에서 반환된 `context` 맵의 지정된 키-값 페어의 문자열화된 값입니다. 예를 들어, 권한 부여자는 다음 `context` 맵을 반환합니다. <pre>"context" : {<br />  "key": "value",<br />  "numKey": 1,<br />  "boolKey": true<br />}</pre> `$context.authorizer.key`를 호출하면 `"value"` 문자열이 반환되고, `$context.authorizer.numKey`를 호출하면 `"1"` 문자열이 반환되고, `$context.authorizer.boolKey`를 호출하면 `"true"` 문자열이 반환됩니다. *속성*의 경우 지원되는 특수 문자는 밑줄 `(_)` 문자뿐입니다. 자세한 내용은 [API Gateway Lambda 권한 부여자 사용](apigateway-use-lambda-authorizer.md) 섹션을 참조하세요.  | 
| \$1context.awsEndpointRequestId |  AWS 엔드포인트의 요청 ID입니다.  | 
| \$1context.deploymentId | API 배포의 ID입니다. | 
| \$1context.domainName |  API를 호출하는 데 사용되는 정식 도메인 이름입니다. 이 이름은 수신되는 `Host` 헤더와 동일해야 합니다.  | 
| \$1context.domainPrefix |  `$context.domainName`의 첫 번째 레이블입니다.  | 
| \$1context.error.message |  API Gateway 오류 메시지가 포함된 문자열입니다. 이 변수는 VTL(Velocity Template Language) 엔진 및 액세스 로깅에서 처리하지 않는 [GatewayResponse](https://docs.aws.amazon.com/apigateway/latest/api/API_GatewayResponse.html) 본문-매핑 템플릿의 간단한 변수 대체에만 사용할 수 있습니다. 자세한 내용은 [CloudWatch 지표로 WebSocket API 실행 모니터링](apigateway-websocket-api-logging.md) 및 [오류 응답을 사용자 지정하도록 게이트웨이 응답 설정](api-gateway-gatewayResponse-definition.md#customize-gateway-responses) 섹션을 참조하세요.  | 
| \$1context.error.messageString | \$1context.error.message의 따옴표 붙은 값, 즉 "\$1context.error.message"입니다. | 
| \$1context.error.responseType |  [GatewayResponse](https://docs.aws.amazon.com/apigateway/latest/api/API_GatewayResponse.html)의 [유형](https://docs.aws.amazon.com/apigateway/latest/api/API_GatewayResponse.html#responseType)입니다. 이 변수는 VTL(Velocity Template Language) 엔진 및 액세스 로깅에서 처리하지 않는 [GatewayResponse](https://docs.aws.amazon.com/apigateway/latest/api/API_GatewayResponse.html) 본문-매핑 템플릿의 간단한 변수 대체에만 사용할 수 있습니다. 자세한 내용은 [CloudWatch 지표로 WebSocket API 실행 모니터링](apigateway-websocket-api-logging.md) 및 [오류 응답을 사용자 지정하도록 게이트웨이 응답 설정](api-gateway-gatewayResponse-definition.md#customize-gateway-responses) 섹션을 참조하세요.  | 
| \$1context.error.validationErrorString |  세부적인 검증 오류 메시지를 포함하는 문자열입니다.  | 
| \$1context.extendedRequestId | API Gateway가 생성하여 API 요청에 할당하는 확장 ID입니다. 확장 요청 ID에는 디버깅 및 문제 해결에 유용한 정보가 포함되어 있습니다. | 
| \$1context.httpMethod |  사용된 HTTP 메서드입니다. 유효한 값에는 `DELETE`, `GET`, `HEAD`, `OPTIONS`, `PATCH`, `POST` 및 `PUT`이 있습니다.  | 
| \$1context.identity.accountId |  요청과 연결된 AWS 계정 ID입니다.  | 
| \$1context.identity.apiKey |  API 키가 필요한 API 메서드의 경우, 이 변수는 메서드 요청과 연결된 API 키입니다. API 키가 필요 없는 메서드의 경우, 이 변수는 null입니다. 자세한 내용은 [API Gateway의 REST API 사용량 계획 및 API 키](api-gateway-api-usage-plans.md) 단원을 참조하세요.  | 
| \$1context.identity.apiKeyId | API 키가 필요한 API 요청과 연결된 API 키 ID입니다. | 
| \$1context.identity.caller |  요청에 서명한 호출자의 보안 주체 ID입니다. IAM 권한 부여를 사용하는 라우팅에 대해 지원됩니다.  | 
| \$1context.identity.cognitoAuthenticationProvider |  요청을 작성한 직접 호출자가 사용한 모든 Amazon Cognito 인증 공급자의 쉼표로 구분된 목록입니다. Amazon Cognito 자격 증명으로 요청을 서명한 경우에만 사용할 수 있습니다. 예를 들어, Amazon Cognito 사용자 풀의 자격 증명의 경우 `cognito-idp. region.amazonaws.com/user_pool_id,cognito-idp.region.amazonaws.com/user_pool_id:CognitoSignIn:token subject claim` 사용 가능한 Amazon Cognito 인증 공급자에 대한 자세한 내용은 Amazon Cognito 개발자 안내서**의 [페더레이션 자격 증명 사용](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity.html)을 참조하세요. | 
| \$1context.identity.cognitoAuthenticationType |  요청을 작성한 호출자의 Amazon Cognito 인증 유형입니다. Amazon Cognito 자격 증명으로 요청을 서명한 경우에만 사용할 수 있습니다. 가능한 값에는 인증 자격 증명에 대한 `authenticated` 및 미인증 자격 증명에 대한 `unauthenticated`이(가) 포함됩니다. | 
| \$1context.identity.cognitoIdentityId |  요청을 작성한 호출자의 Amazon Cognito 자격 증명 ID입니다. Amazon Cognito 자격 증명으로 요청을 서명한 경우에만 사용할 수 있습니다.  | 
| \$1context.identity.cognitoIdentityPoolId |  요청을 작성한 호출자의 Amazon Cognito 자격 증명 풀 ID입니다. Amazon Cognito 자격 증명으로 요청을 서명한 경우에만 사용할 수 있습니다.  | 
| \$1context.identity.principalOrgId |  [AWS 조직 ID](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_org_details.html)입니다.  | 
| \$1context.identity.sourceIp |  API Gateway 엔드포인트를 요청하는 즉시 TCP 연결의 소스 IP 주소입니다.  | 
| \$1context.identity.clientCert.clientCertPem |  상호 TLS 인증 시 클라이언트가 제공한 PEM 인코딩된 클라이언트 인증서입니다. 클라이언트에서 상호 TLS가 활성화된 사용자 지정 도메인 이름을 사용하여 API에 액세스할 때 제공됩니다. 상호 TLS 인증이 실패할 경우 액세스 로그에만 제공됩니다.  | 
| \$1context.identity.clientCert.subjectDN |  클라이언트가 제공하는 인증서의 주체가 갖는 고유 이름입니다. 클라이언트에서 상호 TLS가 활성화된 사용자 지정 도메인 이름을 사용하여 API에 액세스할 때 제공됩니다. 상호 TLS 인증이 실패할 경우 액세스 로그에만 제공됩니다.  | 
| \$1context.identity.clientCert.issuerDN |  클라이언트가 제공하는 인증서의 발행자가 갖는 고유 이름입니다. 클라이언트에서 상호 TLS가 활성화된 사용자 지정 도메인 이름을 사용하여 API에 액세스할 때 제공됩니다. 상호 TLS 인증이 실패할 경우 액세스 로그에만 제공됩니다.  | 
| \$1context.identity.clientCert.serialNumber |  인증서의 일련 번호입니다. 클라이언트에서 상호 TLS가 활성화된 사용자 지정 도메인 이름을 사용하여 API에 액세스할 때 제공됩니다. 상호 TLS 인증이 실패할 경우 액세스 로그에만 제공됩니다.  | 
| \$1context.identity.clientCert.validity.notBefore |  인증서의 유효 기간이 시작되는 날짜입니다. 클라이언트에서 상호 TLS가 활성화된 사용자 지정 도메인 이름을 사용하여 API에 액세스할 때 제공됩니다. 상호 TLS 인증이 실패할 경우 액세스 로그에만 제공됩니다.  | 
| \$1context.identity.clientCert.validity.notAfter |  인증서의 유효 기간이 끝나는 날짜입니다. 클라이언트에서 상호 TLS가 활성화된 사용자 지정 도메인 이름을 사용하여 API에 액세스할 때 제공됩니다. 상호 TLS 인증이 실패할 경우 액세스 로그에만 제공됩니다.  | 
|  \$1context.identity.vpcId | API Gateway 엔드포인트를 요청하는 VPC의 VPC ID입니다. | 
|  \$1context.identity.vpceId |  API Gateway 엔드포인트를 요청하는 VPC 엔드포인트의 VPC 엔드포인트 ID입니다. 프라이빗 API가 있는 경우에만 존재합니다.  | 
| \$1context.identity.user |  리소스 액세스에 대해 권한을 부여할 사용자의 보안 주체 ID입니다. IAM 권한 부여를 사용하는 라우팅에 대해 지원됩니다.  | 
| \$1context.identity.userAgent |  API 호출자의 [https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent) 헤더입니다.  | 
| \$1context.identity.userArn |  인증 후 식별된 실제 사용자의 ARN(Amazon Resource Name)입니다. 자세한 내용은 [https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html) 섹션을 참조하세요.  | 
| \$1context.isCanaryRequest |  요청이 canary로 전달된 경우 `true`, 요청이 canary로 전달되지 않은 경우 `false`를 반환합니다. canary를 활성화한 경우에만 존재합니다. | 
| \$1context.path | 요청 경로입니다. 예를 들어 https://\$1rest-api-id\$1.execute-api.\$1region\$1.amazonaws.com/\$1stage\$1/root/child의 비 프록시 요청 URL의 경우, \$1context.path 값은 /\$1stage\$1/root/child입니다. | 
| \$1context.protocol | 요청 프로토콜입니다(예: HTTP/1.1). API Gateway API는 HTTP/2 요청을 수락할 수 있지만 API Gateway는 HTTP/1.1을 사용하여 백엔드 통합에 요청을 보냅니다. 따라서 클라이언트가 HTTP/2를 사용하는 요청을 보내더라도 요청 프로토콜은 HTTP/1.1로 기록됩니다.   | 
| \$1context.requestId |  요청의 ID입니다. 클라이언트는 이 요청 ID를 재정의할 수 있습니다. API Gateway가 생성하는 고유한 요청 ID에 대한 `$context.extendedRequestId`를 사용합니다.  | 
| \$1context.requestOverride.header.header\$1name |  요청 헤더 재정의입니다. 이 파라미터를 정의하면 **통합 요청(Integration Request)** 창에서 정의한 **HTTP 헤더(HTTP Headers)** 대신에 사용할 헤더가 포함됩니다. 자세한 내용은 [API Gateway에서 REST API에 대한 API 요청, 응답 파라미터, 상태 코드 재정의](apigateway-override-request-response-parameters.md) 단원을 참조하세요.  | 
| \$1context.requestOverride.path.path\$1name |  요청 경로 재정의입니다. 이 파라미터를 정의하면 **통합 요청(Integration Request)** 창에서 정의한 **URL 경로 파라미터(URL Path Parameters)** 대신에 사용할 요청 경로가 포함됩니다. 자세한 내용은 [API Gateway에서 REST API에 대한 API 요청, 응답 파라미터, 상태 코드 재정의](apigateway-override-request-response-parameters.md) 단원을 참조하세요.  | 
| \$1context.requestOverride.querystring.querystring\$1name |  요청 쿼리 문자열 재정의입니다. 이 파라미터를 정의하면 **통합 요청(Integration Request)** 창에서 정의한 **URL 쿼리 문자열 파라미터(URL Query String Parameters)** 대신에 사용할 요청 쿼리 문자열이 포함됩니다. 자세한 내용은 [API Gateway에서 REST API에 대한 API 요청, 응답 파라미터, 상태 코드 재정의](apigateway-override-request-response-parameters.md) 단원을 참조하세요.  | 
| \$1context.responseOverride.header.header\$1name | 응답 헤더 재정의입니다. 이 파라미터를 정의하면 통합 요청(Integration Response) 창에서 기본 매핑(Default mapping)으로 정의한 응답 헤더(Response header) 대신에 반환할 헤더가 포함됩니다. 자세한 내용은 [API Gateway에서 REST API에 대한 API 요청, 응답 파라미터, 상태 코드 재정의](apigateway-override-request-response-parameters.md) 단원을 참조하세요. | 
| \$1context.responseOverride.status | 응답 상태 코드 재정의입니다. 이 파라미터를 정의하면 통합 요청(Integration Response) 창에서 기본 매핑(Default mapping)으로 정의한 메서드 응답 상태(Method response status) 대신에 반환할 상태 코드가 포함됩니다. 자세한 내용은 [API Gateway에서 REST API에 대한 API 요청, 응답 파라미터, 상태 코드 재정의](apigateway-override-request-response-parameters.md) 단원을 참조하세요. | 
| \$1context.requestTime | [CLF](https://httpd.apache.org/docs/current/logs.html#common) 형식 요청 시간(dd/MMM/yyyy:HH:mm:ss \$1-hhmm)입니다. | 
| \$1context.requestTimeEpoch | [Epoch](https://en.wikipedia.org/wiki/Unix_time) 형식 요청 시간(밀리초)입니다. | 
| \$1context.resourceId |  API Gateway가 리소스에 할당하는 식별자입니다.  | 
| \$1context.resourcePath |  리소스에 대한 경로입니다. 예를 들어 `https://{rest-api-id}.execute-api.{region}.amazonaws.com/{stage}/root/child`의 비 프록시 요청 URI의 경우, `$context.resourcePath` 값은 `/root/child`입니다. 자세한 내용은 [자습서: HTTP 비 프록시 통합을 통해 REST API 생성](api-gateway-create-api-step-by-step.md) 단원을 참조하세요.  | 
| \$1context.stage |  API 요청의 개발 단계입니다(예: `Beta` 또는 `Prod`).  | 
| \$1context.wafResponseCode |  [AWS WAF](https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html)에서 받은 응답: `WAF_ALLOW` 또는 `WAF_BLOCK`. 스테이지가 웹 ACL과 연결되어 있지 않은 경우 설정되지 않습니다. 자세한 내용은 [API Gateway에서 AWS WAF를 사용하여 REST API 보호](apigateway-control-access-aws-waf.md) 단원을 참조하세요.  | 
| \$1context.webaclArn |  요청을 허용할지 차단할지 결정하는 데 사용되는 웹 ACL의 전체 ARN입니다. 스테이지가 웹 ACL과 연결되어 있지 않은 경우 설정되지 않습니다. 자세한 내용은 [API Gateway에서 AWS WAF를 사용하여 REST API 보호](apigateway-control-access-aws-waf.md) 섹션을 참조하세요.  | 

## 입력 변수
<a name="input-variable-reference"></a>

다음 대소문자 구분 `$input` 변수를 사용하여 메서드 요청 페이로드 및 메서드 요청 파라미터를 참조할 수 있습니다. 다음과 같은 기능을 사용할 수 있습니다.


| 변수 및 함수 | 설명 | 
| --- | --- | 
| \$1input.body |  원시 요청 페이로드를 문자열로 반환합니다. `$input.body`를 사용하여 전체 부동 소수점 숫자를 보존할 수 있습니다(예: `10.00`). | 
| \$1input.json(x) | 이 함수는 JSONPath 표현식을 평가하고 결과를 JSON 문자열로 반환합니다. 예를 들어, `$input.json('$.pets')`은 `pets` 구조를 나타내는 JSON 문자열을 반환합니다. JSONPath에 대한 자세한 내용은 [JSONPath](https://goessner.net/articles/JsonPath/) 또는 [Java용 JSONPath](https://github.com/json-path/JsonPath)를 참조하세요. | 
| \$1input.params() |  모든 요청 파라미터의 맵을 반환합니다. 잠재적인 주입 공격을 방지하기 위해 `$util.escapeJavaScript`을(를) 사용하여 결과를 삭제하는 것이 좋습니다. 요청 삭제를 완벽하게 제어하려면 템플릿 없이 프록시 통합을 사용하고 통합에서 요청 삭제를 처리합니다. | 
| \$1input.params(x) | 파라미터 이름 문자열 `x`가 지정된 경로, 쿼리 문자열 또는 헤더 값(순서대로 검색됨)에서 메서드 요청 파라미터 값을 반환합니다. 잠재적인 주입 공격을 방지하기 위해 `$util.escapeJavaScript`을(를) 사용하여 파라미터를 삭제하는 것이 좋습니다. 파라미터 삭제를 완벽하게 제어하려면 템플릿 없이 프록시 통합을 사용하고 통합에서 요청 삭제를 처리합니다. | 
| \$1input.path(x) | JSONPath 표현식 문자열 (`x`)을 가져와서 결과의 JSON 객체로 반환합니다. 이를 통해 기본적으로 [Apache Velocity Template Language(VTL)](https://velocity.apache.org/engine/devel/vtl-reference.html)에서 페이로드 요소에 액세스하고 조작할 수 있습니다. 예를 들어, `$input.path('$.pets')` 표현식이 다음과 같은 객체를 반환할 경우: <pre>[<br />  { <br />    "id": 1, <br />    "type": "dog", <br />    "price": 249.99 <br />  }, <br />  { <br />    "id": 2, <br />    "type": "cat", <br />    "price": 124.99 <br />  }, <br />  { <br />    "id": 3, <br />    "type": "fish", <br />    "price": 0.99 <br />  } <br />]</pre> `$input.path('$.pets').size()`는 을 반환합니다.`"3"` JSONPath에 대한 자세한 내용은 [JSONPath](https://goessner.net/articles/JsonPath/) 또는 [Java용 JSONPath](https://github.com/json-path/JsonPath)를 참조하세요. | 

## 단계 변수
<a name="stagevariables-template-reference"></a>

메서드 통합에서 다음 단계 변수를 ARN 및 URL의 자리 표시자로 사용할 수 있습니다. 자세한 내용은 [API Gateway에서 REST API용 스테이지 변수 사용](stage-variables.md) 섹션을 참조하세요.


| 구문 | 설명 | 
| --- | --- | 
| \$1stageVariables.variable\$1name,\$1stageVariables['variable\$1name'] 또는 \$1\$1stageVariables['variable\$1name']\$1  |  *variable\$1name*은 단계 변수 이름을 나타냅니다.  | 

## 유틸리티 변수
<a name="util-template-reference"></a>

다음 대소문자 구분 `$util` 변수를 사용하여 매핑 탬플릿용 유틸리티 함수를 사용할 수 있습니다. 달리 지정하지 않는 한, 기본 문자 집합은 UTF-8입니다.


| 함수 | 설명 | 
| --- | --- | 
| \$1util.escapeJavaScript() |  JavaScript 문자열 규칙을 사용하여 문자열의 문자를 이스케이프합니다.  이 함수는 일반 작은따옴표(`'`)를 이스케이프된 작은따옴표(`\'`)로 변환합니다. 그러나 이스케이프된 작은따옴표는 JSON에서 유효하지 않습니다. 따라서 이 함수의 결과를 JSON 속성에서 사용할 경우 이스케이프된 작은따옴표(`\'`)를 다시 일반 작은따옴표(`'`)로 변환해야 합니다. 방법은 다음 예제와 같습니다:  <pre> "input" : "$util.escapeJavaScript(data).replaceAll("\\'","'")"</pre>   | 
| \$1util.parseJson() |   "문자열화된" JSON을 가져와서 결과의 객체 표현을 반환합니다. 이 함수의 결과를 사용하여 기본적으로 Apache VTL(Velocity Template Language)에서 페이로드 요소에 액세스하고 조작할 수 있습니다. 예를 들어 다음과 같은 페이로드가 있고  <pre>{"errorMessage":"{\"key1\":\"var1\",\"key2\":{\"arr\":[1,2,3]}}"}</pre>  다음 매핑 템플릿을 사용하는 경우  <pre>#set ($errorMessageObj = $util.parseJson($input.path('$.errorMessage')))<br />{<br />   "errorMessageObjKey2ArrVal" : $errorMessageObj.key2.arr[0]<br />}<br /></pre> 출력은 다음과 같습니다. <pre>{<br />   "errorMessageObjKey2ArrVal" : 1<br />}<br /></pre>  | 
| \$1util.urlEncode() | 문자열을 "application/x-www-form-urlencoded" 형식으로 변환합니다. | 
| \$1util.urlDecode() | "application/x-www-form-urlencoded" 문자열을 디코딩합니다. | 
| \$1util.base64Encode() | 데이터를 base64 인코딩 문자열로 인코딩합니다. | 
| \$1util.base64Decode() | 데이터를 base64 인코딩 문자열에서 디코딩합니다. | 