API Gateway & Lambda
🔥 Vibe Prompt
"Create a serverless CRUD API with API Gateway HTTP API + Lambda + DynamoDB."
import boto3, json, os
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(os.environ['TABLE_NAME'])
def lambda_handler(event, context):
method = event['requestContext']['http']['method']
path = event['requestContext']['http']['path']
if method == 'GET' and path == '/items':
items = table.scan()['Items']
return {"statusCode": 200, "body": json.dumps(items)}
elif method == 'POST' and path == '/items':
body = json.loads(event['body'])
table.put_item(Item=body)
return {"statusCode": 201, "body": json.dumps(body)}
elif method == 'GET' and path.startswith('/items/'):
item_id = path.split('/')[-1]
item = table.get_item(Key={'id': item_id}).get('Item')
if item:
return {"statusCode": 200, "body": json.dumps(item)}
return {"statusCode": 404, "body": "Not found"}
elif method == 'DELETE' and path.startswith('/items/'):
item_id = path.split('/')[-1]
table.delete_item(Key={'id': item_id})
return {"statusCode": 204, "body": ""}
return {"statusCode": 400, "body": "Bad request"}
Terraform
resource "aws_apigatewayv2_api" "http" {
name = "serverless-api"
protocol_type = "HTTP"
cors_configuration {
allow_origins = ["*"]
allow_methods = ["GET", "POST", "PUT", "DELETE"]
}
}
resource "aws_apigatewayv2_integration" "lambda" {
api_id = aws_apigatewayv2_api.http.id
integration_type = "AWS_PROXY"
integration_uri = aws_lambda_function.api.arn
}
resource "aws_apigatewayv2_route" "proxy" {
api_id = aws_apigatewayv2_api.http.id
route_key = "$default"
target = "integrations/${aws_apigatewayv2_integration.lambda.id}"
}
Key Concepts
- HTTP API = cheaper ($), simpler than REST API
- $default route catches all paths
- Lambda proxy integration passes full request
- CORS must be configured at API Gateway level
Cost Comparison
| API Type | Cost (1M requests) | Features | |----------|-------------------|----------| | HTTP API | ~$1.00 | Lambda proxy, CORS, JWT | | REST API | ~$3.50 | WAF, API keys, usage plans |
Key Points
- Understand the core concepts thoroughly
- Practice with hands-on code examples
- Apply knowledge to real-world problems
- Review and reinforce through exercises
Further Learning
- Official documentation
- Open source projects on GitHub
- Community forums and discussions
- Related courses and tutorials
為什麼需要 API Gateway?
直接把 Lambda 暴露給網際網路是不安全的。你需要:
- HTTP 端點:把 Lambda 函式變成 REST API
- 請求驗證:檢查 API Key、JWT Token
- 速率限制:防止被濫用
- CORS:允許前端跨域請求
- 請求轉換:將 HTTP 請求轉換為 Lambda 輸入格式
- 回應轉換:將 Lambda 回傳值轉換為 HTTP 回應
這些功能全部由 API Gateway 提供,你不需要寫任何程式碼。
API Gateway 的兩種 API 類型
| 類型 | 適合場景 | 費用 | 延遲 | |:----:|:--------:|:----:|:----:| | REST API | 需要 API Keys、Usage Plans、快取 | 較高 | 中 | | HTTP API | 簡單的代理到 Lambda/HTTP 端點 | 較低(約 REST 的 70%) | 更低 |
生產環境的 API Gateway 配置
# CloudFormation / SAM 範例
MyApi:
Type: AWS::Serverless::Api
Properties:
StageName: prod
Auth:
DefaultAuthorizer: JWTAuthorizer
Authorizers:
JWTAuthorizer:
JwtConfiguration:
issuer: https://cognito-idp.us-west-2.amazonaws.com/us-west-2_xxx
audience:
- xxxxxxxxxxxxxxxxxxxxxxxxxx
IdentitySource: $request.header.Authorization
MethodSettings:
- ResourcePath: /*
HttpMethod: POST
ThrottlingRateLimit: 100
ThrottlingBurstLimit: 50
下一章預告:進入 DynamoDB
API Gateway + Lambda 讓你建立了無伺服器的 API。但 API 需要資料——下一章將深入 DynamoDB,學習如何在無伺服器架構中設計 NoSQL 資料表、選擇 Partition Key 與 Sort Key、以及使用 GSI 支援多種查詢模式。