AWS API Gateway는 RESTful API, HTTP API, WebSocket API를 생성·배포·관리하는 완전 관리형 서비스다. Lambda와 통합하면 서버리스 백엔드를 손쉽게 구성할 수 있다.
API 유형 비교
| 항목 | REST API | HTTP API | WebSocket API |
|---|
| 기능 | 풍부 (캐싱, WAF, API 키) | 경량, 저지연 | 양방향 통신 |
| 비용 | 높음 | 낮음 (70%) | 연결/메시지당 |
| Lambda 통합 | 프록시/커스텀 | 프록시만 | 지원 |
| JWT 인가 | 커스텀 인증기 | 기본 제공 | 지원 |
| VPC 링크 | 지원 | 지원 | 미지원 |
Lambda 프록시 통합
python
# Lambda 핸들러 (프록시 통합)
import json
def handler(event, context):
method = event['httpMethod']
path = event['path']
body = json.loads(event.get('body') or '{}')
headers = event.get('headers', {})
# 처리 로직
result = process_request(method, path, body)
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
},
'body': json.dumps(result),
}
CDK로 API Gateway 구성
typescript
import * as apigw from 'aws-cdk-lib/aws-apigateway';
import * as lambda from 'aws-cdk-lib/aws-lambda';
const api = new apigw.RestApi(this, 'OrdersApi', {
restApiName: 'orders-api',
deployOptions: {
stageName: 'prod',
cachingEnabled: true,
cacheClusterSize: '0.5',
methodOptions: {
'/*/*': { cachingEnabled: true, cacheTtl: cdk.Duration.minutes(5) },
},
},
});
const ordersResource = api.root.addResource('orders');
ordersResource.addMethod('GET', new apigw.LambdaIntegration(listOrdersFn));
ordersResource.addMethod('POST', new apigw.LambdaIntegration(createOrderFn));
// JWT 인증기
const authorizer = new apigw.CognitoUserPoolsAuthorizer(this, 'Authorizer', {
cognitoUserPools: [userPool],
});
ordersResource.addMethod('DELETE', new apigw.LambdaIntegration(deleteOrderFn), {
authorizer,
authorizationType: apigw.AuthorizationType.COGNITO,
});
API Gateway 스로틀링 및 할당량
bash
# 사용 계획 및 API 키 설정
aws apigateway create-usage-plan --name "standard-plan" --throttle burstLimit=100,rateLimit=50 --quota limit=10000,period=MONTH
매핑 템플릿 (VTL)
velocity
## 요청 변환 (VTL)
# set($body = $util.parseJson($input.body))
{
"orderId": "$body.order_id",
"customerId": "$context.authorizer.principalId",
"amount": $body.total
}