api-gateway
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAWS API Gateway
AWS API Gateway
Amazon API Gateway is a fully managed service for creating, publishing, and securing APIs at any scale. Supports REST APIs, HTTP APIs, and WebSocket APIs.
Amazon API Gateway 是一项全托管服务,可用于创建、发布和保护任意规模的API。支持REST API、HTTP API和WebSocket API。
Table of Contents
目录
Core Concepts
核心概念
API Types
API类型
| Type | Description | Use Case |
|---|---|---|
| HTTP API | Low-latency, cost-effective | Simple APIs, Lambda proxy |
| REST API | Full-featured, more control | Complex APIs, transformation |
| WebSocket API | Bidirectional communication | Real-time apps, chat |
| 类型 | 描述 | 适用场景 |
|---|---|---|
| HTTP API | 低延迟、高性价比 | 简单API、Lambda代理 |
| REST API | 功能全面、可控性强 | 复杂API、请求/响应转换 |
| WebSocket API | 双向通信 | 实时应用、聊天系统 |
Key Components
关键组件
- Resources: URL paths (/users, /orders/{id})
- Methods: HTTP verbs (GET, POST, PUT, DELETE)
- Integrations: Backend connections (Lambda, HTTP, AWS services)
- Stages: Deployment environments (dev, prod)
- 资源:URL路径(/users、/orders/{id})
- 方法:HTTP动词(GET、POST、PUT、DELETE)
- 集成:后端连接(Lambda、HTTP、AWS服务)
- 部署阶段:部署环境(dev、prod)
Integration Types
集成类型
| Type | Description |
|---|---|
| Lambda Proxy | Pass-through to Lambda (recommended) |
| Lambda Custom | Transform request/response |
| HTTP Proxy | Pass-through to HTTP endpoint |
| AWS Service | Direct integration with AWS services |
| Mock | Return static response |
| 类型 | 描述 |
|---|---|
| Lambda Proxy | 直接传递请求到Lambda(推荐) |
| Lambda Custom | 转换请求/响应 |
| HTTP Proxy | 直接传递请求到HTTP端点 |
| AWS Service | 与AWS服务直接集成 |
| Mock | 返回静态响应 |
Common Patterns
常见模式
Create HTTP API with Lambda
创建带Lambda的HTTP API
AWS CLI:
bash
undefinedAWS CLI:
bash
undefinedCreate HTTP API
Create HTTP API
aws apigatewayv2 create-api
--name my-api
--protocol-type HTTP
--target arn:aws:lambda:us-east-1:123456789012:function:MyFunction
--name my-api
--protocol-type HTTP
--target arn:aws:lambda:us-east-1:123456789012:function:MyFunction
aws apigatewayv2 create-api
--name my-api
--protocol-type HTTP
--target arn:aws:lambda:us-east-1:123456789012:function:MyFunction
--name my-api
--protocol-type HTTP
--target arn:aws:lambda:us-east-1:123456789012:function:MyFunction
Get API endpoint
Get API endpoint
aws apigatewayv2 get-api --api-id abc123 --query 'ApiEndpoint'
**SAM Template:**
```yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
MyApi:
Type: AWS::Serverless::HttpApi
Properties:
StageName: prod
MyFunction:
Type: AWS::Serverless::Function
Properties:
Handler: app.handler
Runtime: python3.12
Events:
ApiEvent:
Type: HttpApi
Properties:
ApiId: !Ref MyApi
Path: /items
Method: GETaws apigatewayv2 get-api --api-id abc123 --query 'ApiEndpoint'
**SAM模板:**
```yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
MyApi:
Type: AWS::Serverless::HttpApi
Properties:
StageName: prod
MyFunction:
Type: AWS::Serverless::Function
Properties:
Handler: app.handler
Runtime: python3.12
Events:
ApiEvent:
Type: HttpApi
Properties:
ApiId: !Ref MyApi
Path: /items
Method: GETCreate REST API with Lambda Proxy
创建带Lambda代理的REST API
bash
undefinedbash
undefinedCreate REST API
Create REST API
aws apigateway create-rest-api
--name my-rest-api
--endpoint-configuration types=REGIONAL
--name my-rest-api
--endpoint-configuration types=REGIONAL
API_ID=abc123
aws apigateway create-rest-api
--name my-rest-api
--endpoint-configuration types=REGIONAL
--name my-rest-api
--endpoint-configuration types=REGIONAL
API_ID=abc123
Get root resource ID
Get root resource ID
ROOT_ID=$(aws apigateway get-resources --rest-api-id $API_ID --query 'items[0].id' --output text)
ROOT_ID=$(aws apigateway get-resources --rest-api-id $API_ID --query 'items[0].id' --output text)
Create resource
Create resource
aws apigateway create-resource
--rest-api-id $API_ID
--parent-id $ROOT_ID
--path-part items
--rest-api-id $API_ID
--parent-id $ROOT_ID
--path-part items
RESOURCE_ID=xyz789
aws apigateway create-resource
--rest-api-id $API_ID
--parent-id $ROOT_ID
--path-part items
--rest-api-id $API_ID
--parent-id $ROOT_ID
--path-part items
RESOURCE_ID=xyz789
Create method
Create method
aws apigateway put-method
--rest-api-id $API_ID
--resource-id $RESOURCE_ID
--http-method GET
--authorization-type NONE
--rest-api-id $API_ID
--resource-id $RESOURCE_ID
--http-method GET
--authorization-type NONE
aws apigateway put-method
--rest-api-id $API_ID
--resource-id $RESOURCE_ID
--http-method GET
--authorization-type NONE
--rest-api-id $API_ID
--resource-id $RESOURCE_ID
--http-method GET
--authorization-type NONE
Create Lambda integration
Create Lambda integration
aws apigateway put-integration
--rest-api-id $API_ID
--resource-id $RESOURCE_ID
--http-method GET
--type AWS_PROXY
--integration-http-method POST
--uri arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:123456789012:function:MyFunction/invocations
--rest-api-id $API_ID
--resource-id $RESOURCE_ID
--http-method GET
--type AWS_PROXY
--integration-http-method POST
--uri arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:123456789012:function:MyFunction/invocations
aws apigateway put-integration
--rest-api-id $API_ID
--resource-id $RESOURCE_ID
--http-method GET
--type AWS_PROXY
--integration-http-method POST
--uri arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:123456789012:function:MyFunction/invocations
--rest-api-id $API_ID
--resource-id $RESOURCE_ID
--http-method GET
--type AWS_PROXY
--integration-http-method POST
--uri arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:123456789012:function:MyFunction/invocations
Deploy to stage
Deploy to stage
aws apigateway create-deployment
--rest-api-id $API_ID
--stage-name prod
--rest-api-id $API_ID
--stage-name prod
undefinedaws apigateway create-deployment
--rest-api-id $API_ID
--stage-name prod
--rest-api-id $API_ID
--stage-name prod
undefinedLambda Handler for API Gateway
API Gateway的Lambda处理函数
python
import json
def handler(event, context):
# HTTP API event
http_method = event.get('requestContext', {}).get('http', {}).get('method')
path = event.get('rawPath', '')
query_params = event.get('queryStringParameters', {})
body = event.get('body', '')
if body and event.get('isBase64Encoded'):
import base64
body = base64.b64decode(body).decode('utf-8')
# Process request
response_body = {'message': 'Success', 'path': path}
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json'
},
'body': json.dumps(response_body)
}python
import json
def handler(event, context):
# HTTP API event
http_method = event.get('requestContext', {}).get('http', {}).get('method')
path = event.get('rawPath', '')
query_params = event.get('queryStringParameters', {})
body = event.get('body', '')
if body and event.get('isBase64Encoded'):
import base64
body = base64.b64decode(body).decode('utf-8')
# Process request
response_body = {'message': 'Success', 'path': path}
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json'
},
'body': json.dumps(response_body)
}Configure CORS
配置CORS
HTTP API:
bash
aws apigatewayv2 update-api \
--api-id abc123 \
--cors-configuration '{
"AllowOrigins": ["https://example.com"],
"AllowMethods": ["GET", "POST", "PUT", "DELETE"],
"AllowHeaders": ["Content-Type", "Authorization"],
"MaxAge": 86400
}'REST API:
bash
undefinedHTTP API:
bash
aws apigatewayv2 update-api \
--api-id abc123 \
--cors-configuration '{
"AllowOrigins": ["https://example.com"],
"AllowMethods": ["GET", "POST", "PUT", "DELETE"],
"AllowHeaders": ["Content-Type", "Authorization"],
"MaxAge": 86400
}'REST API:
bash
undefinedEnable CORS on resource
Enable CORS on resource
aws apigateway put-method
--rest-api-id $API_ID
--resource-id $RESOURCE_ID
--http-method OPTIONS
--authorization-type NONE
--rest-api-id $API_ID
--resource-id $RESOURCE_ID
--http-method OPTIONS
--authorization-type NONE
aws apigateway put-integration
--rest-api-id $API_ID
--resource-id $RESOURCE_ID
--http-method OPTIONS
--type MOCK
--request-templates '{"application/json": "{"statusCode": 200}"}'
--rest-api-id $API_ID
--resource-id $RESOURCE_ID
--http-method OPTIONS
--type MOCK
--request-templates '{"application/json": "{"statusCode": 200}"}'
aws apigateway put-method-response
--rest-api-id $API_ID
--resource-id $RESOURCE_ID
--http-method OPTIONS
--status-code 200
--response-parameters '{ "method.response.header.Access-Control-Allow-Headers": true, "method.response.header.Access-Control-Allow-Methods": true, "method.response.header.Access-Control-Allow-Origin": true }'
--rest-api-id $API_ID
--resource-id $RESOURCE_ID
--http-method OPTIONS
--status-code 200
--response-parameters '{ "method.response.header.Access-Control-Allow-Headers": true, "method.response.header.Access-Control-Allow-Methods": true, "method.response.header.Access-Control-Allow-Origin": true }'
aws apigateway put-integration-response
--rest-api-id $API_ID
--resource-id $RESOURCE_ID
--http-method OPTIONS
--status-code 200
--response-parameters '{ "method.response.header.Access-Control-Allow-Headers": "'''Content-Type,Authorization'''", "method.response.header.Access-Control-Allow-Methods": "'''GET,POST,PUT,DELETE,OPTIONS'''", "method.response.header.Access-Control-Allow-Origin": "'''*'''" }'
--rest-api-id $API_ID
--resource-id $RESOURCE_ID
--http-method OPTIONS
--status-code 200
--response-parameters '{ "method.response.header.Access-Control-Allow-Headers": "'''Content-Type,Authorization'''", "method.response.header.Access-Control-Allow-Methods": "'''GET,POST,PUT,DELETE,OPTIONS'''", "method.response.header.Access-Control-Allow-Origin": "'''*'''" }'
undefinedaws apigateway put-method
--rest-api-id $API_ID
--resource-id $RESOURCE_ID
--http-method OPTIONS
--authorization-type NONE
--rest-api-id $API_ID
--resource-id $RESOURCE_ID
--http-method OPTIONS
--authorization-type NONE
aws apigateway put-integration
--rest-api-id $API_ID
--resource-id $RESOURCE_ID
--http-method OPTIONS
--type MOCK
--request-templates '{"application/json": "{"statusCode": 200}"}'
--rest-api-id $API_ID
--resource-id $RESOURCE_ID
--http-method OPTIONS
--type MOCK
--request-templates '{"application/json": "{"statusCode": 200}"}'
aws apigateway put-method-response
--rest-api-id $API_ID
--resource-id $RESOURCE_ID
--http-method OPTIONS
--status-code 200
--response-parameters '{ "method.response.header.Access-Control-Allow-Headers": true, "method.response.header.Access-Control-Allow-Methods": true, "method.response.header.Access-Control-Allow-Origin": true }'
--rest-api-id $API_ID
--resource-id $RESOURCE_ID
--http-method OPTIONS
--status-code 200
--response-parameters '{ "method.response.header.Access-Control-Allow-Headers": true, "method.response.header.Access-Control-Allow-Methods": true, "method.response.header.Access-Control-Allow-Origin": true }'
aws apigateway put-integration-response
--rest-api-id $API_ID
--resource-id $RESOURCE_ID
--http-method OPTIONS
--status-code 200
--response-parameters '{ "method.response.header.Access-Control-Allow-Headers": "'''Content-Type,Authorization'''", "method.response.header.Access-Control-Allow-Methods": "'''GET,POST,PUT,DELETE,OPTIONS'''", "method.response.header.Access-Control-Allow-Origin": "'''*'''" }'
--rest-api-id $API_ID
--resource-id $RESOURCE_ID
--http-method OPTIONS
--status-code 200
--response-parameters '{ "method.response.header.Access-Control-Allow-Headers": "'''Content-Type,Authorization'''", "method.response.header.Access-Control-Allow-Methods": "'''GET,POST,PUT,DELETE,OPTIONS'''", "method.response.header.Access-Control-Allow-Origin": "'''*'''" }'
undefinedJWT Authorization (HTTP API)
JWT授权(HTTP API)
bash
aws apigatewayv2 create-authorizer \
--api-id abc123 \
--name jwt-authorizer \
--authorizer-type JWT \
--identity-source '$request.header.Authorization' \
--jwt-configuration '{
"Issuer": "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_abc123",
"Audience": ["client-id"]
}'bash
aws apigatewayv2 create-authorizer \
--api-id abc123 \
--name jwt-authorizer \
--authorizer-type JWT \
--identity-source '$request.header.Authorization' \
--jwt-configuration '{
"Issuer": "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_abc123",
"Audience": ["client-id"]
}'CLI Reference
CLI参考
HTTP API (apigatewayv2)
HTTP API(apigatewayv2)
| Command | Description |
|---|---|
| Create API |
| List APIs |
| Create route |
| Create integration |
| Create stage |
| Create authorizer |
| 命令 | 描述 |
|---|---|
| 创建API |
| 列出所有API |
| 创建路由 |
| 创建集成 |
| 创建部署阶段 |
| 创建授权器 |
REST API (apigateway)
REST API(apigateway)
| Command | Description |
|---|---|
| Create API |
| List APIs |
| Create resource |
| Create method |
| Create integration |
| Deploy API |
| 命令 | 描述 |
|---|---|
| 创建API |
| 列出所有API |
| 创建资源 |
| 创建方法 |
| 创建集成 |
| 部署API |
Best Practices
最佳实践
Performance
性能优化
- Use HTTP APIs for simple use cases (70% cheaper, lower latency)
- Enable caching for REST APIs
- Use regional endpoints unless global distribution needed
- Implement pagination for list endpoints
- 使用HTTP API处理简单场景(成本低70%,延迟更低)
- 为REST API启用缓存
- 除非需要全球分发,否则使用区域端点
- 为列表类端点实现分页
Security
安全防护
- Use authorization on all endpoints
- Enable WAF for REST APIs
- Use API keys for rate limiting (not authentication)
- Enable access logging
- Use HTTPS only
- 为所有端点配置授权
- 为REST API启用WAF
- 使用API密钥实现速率限制(而非身份验证)
- 启用访问日志
- 仅使用HTTPS
Reliability
可靠性保障
- Set up throttling to protect backends
- Configure timeout appropriately
- Use canary deployments for updates
- Monitor with CloudWatch
- 设置限流规则保护后端服务
- 合理配置超时时间
- 使用金丝雀发布进行更新
- 通过CloudWatch监控API状态
Troubleshooting
故障排查
403 Forbidden
403 Forbidden错误
Causes:
- Missing authorization
- Invalid API key
- WAF blocking
- Resource policy denying
Debug:
bash
undefined可能原因:
- 缺少授权配置
- API密钥无效
- WAF拦截请求
- 资源策略拒绝访问
排查命令:
bash
undefinedCheck API key
Check API key
aws apigateway get-api-key --api-key abc123 --include-value
aws apigateway get-api-key --api-key abc123 --include-value
Check authorizer
Check authorizer
aws apigatewayv2 get-authorizer --api-id abc123 --authorizer-id xyz789
undefinedaws apigatewayv2 get-authorizer --api-id abc123 --authorizer-id xyz789
undefined502 Bad Gateway
502 Bad Gateway错误
Causes:
- Lambda error
- Integration timeout
- Invalid response format
Lambda response format:
python
undefined可能原因:
- Lambda函数执行出错
- 集成超时
- 响应格式无效
Lambda响应格式要求:
python
undefinedCorrect format
Correct format
return {
'statusCode': 200,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps({'message': 'success'})
}
return {
'statusCode': 200,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps({'message': 'success'})
}
Wrong - missing statusCode
Wrong - missing statusCode
return {'message': 'success'}
undefinedreturn {'message': 'success'}
undefined504 Gateway Timeout
504 Gateway Timeout错误
Causes:
- Backend timeout (Lambda max 29 seconds for REST API)
- Integration timeout too short
Solutions:
- Increase Lambda timeout
- Use async processing for long operations
- Increase integration timeout (max 29s for REST, 30s for HTTP)
可能原因:
- 后端服务超时(REST API的Lambda最大超时为29秒)
- 集成超时时间设置过短
解决方案:
- 增加Lambda函数超时时间
- 对长耗时操作使用异步处理
- 延长集成超时时间(REST API最大29秒,HTTP API最大30秒)
CORS Errors
CORS错误
Debug:
- Check OPTIONS method exists
- Verify headers in response
- Check origin matches allowed origins
排查要点:
- 确认OPTIONS方法已配置
- 验证响应头是否正确
- 检查请求源是否在允许的源列表中