MappingTemplates
1 AWS API Gateway Mapping Templates 심층 이해
- AWS API Gateway의 Mapping Templates는 API 요청과 응답 데이터를 변환하는 강력한 도구입니다.
- 이 기능은 주로 통합(Integration) 단계에서 사용되며, 클라이언트와 백엔드 서비스 간의 데이터 형식 차이를 해결합니다.
- Mapping Templates는 Apache Velocity Template Language(VTL)를 기반으로 하며, JSON 데이터 조작에 특화되어 있습니다.
2 API Gateway 요청/응답 흐름 이해
- API Gateway에서 요청과 응답의 흐름은 다음과 같습니다:
- Method Request
- Integration Request
- Backend
- Integration Response
- Method Response
- Method Request/Response: API의 구조와 인증을 정의합니다.
- Integration Request/Response: 실제 데이터 변환이 일어나는 단계입니다.
- Mapping Templates는 Integration Request와 Integration Response 단계에서 적용됩니다.
3 Mapping Templates의 적용 위치
3.1 Integration Request에서의 Mapping Template
- 클라이언트의 요청을 백엔드 서비스가 이해할 수 있는 형식으로 변환합니다.
- 예: JSON 형식의 요청 본문을 XML로 변환하거나, 요청 파라미터를 재구성할 때 사용합니다.
3.2 Integration Response에서의 Mapping Template
- 백엔드 서비스의 응답을 클라이언트가 기대하는 형식으로 변환합니다.
- 예: XML 응답을 JSON으로 변환하거나, 응답 데이터 구조를 재구성할 때 사용합니다.
4 Mapping Templates 작성 방법
- VTL과 JSONPath 표현식을 사용하여 작성합니다.
기본 Mapping Template 구조
#set($inputRoot = $input.path('$'))
{
"transformedKey": "$inputRoot.originalKey",
"newValue": "$inputRoot.someValue.toUpperCase()"
}
$input.path('$')
: 입력 JSON의 루트에 접근합니다.$inputRoot.originalKey
: JSON 경로로 특정 값에 접근합니다.$inputRoot.someValue.toUpperCase()
: 값을 변환합니다.
5 Mapping Templates 사용 예시
5.1 Integration Request Mapping 예시
- 클라이언트 요청을 백엔드 형식으로 변환하는 예시입니다.
클라이언트 요청 데이터
{
"name": "John Doe",
"age": 30
}
Mapping Template (Integration Request)
#set($inputRoot = $input.path('$'))
{
"user": {
"fullName": "$inputRoot.name",
"yearOfBirth": $util.escapeJavaScript("$input.json('$.age')"),
"requestTime": "$context.requestTime"
}
}