关于 api-gateway
用于通过 AWS API Gateway 创建和运行 API 的实用参考技能,涵盖 HTTP、REST 和 WebSocket API、后端集成、授权、部署及故障排查。
主要功能
- 01HTTP、REST 和 WebSocket API
- 02后端集成模式
- 03CORS 与 JWT 授权
- 04API 部署命令
- 05错误与超时诊断
适用场景
- 01创建由 Lambda 支持的 HTTP API
- 02配置 CORS 或 JWT 授权
- 03排查网关错误
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ itsmostafa/ aws-agent-skills --skill api-gateway安装后在 Claude Code 中输入/api-gateway确认已加载。
附带文件integration-patterns.md
详细介绍
AWS API Gateway
Amazon API Gateway 是一项完全托管的服务,可用于创建、发布和保护任意规模的 API。支持 REST API、HTTP API 和 WebSocket API。
目录
核心概念
API 类型
| 类型 | 描述 | 用例 |
|---|---|---|
| HTTP API | 延迟低、成本效益高 | 简单 API、Lambda 代理 |
| REST API | 功能全面、控制力更强 | 复杂 API、转换 |
| WebSocket API | 双向通信 | 实时应用、聊天 |
关键组件
- 资源:URL 路径(/users、/orders/{id})
- 方法:HTTP 动词(GET、POST、PUT、DELETE)
- 集成:后端连接(Lambda、HTTP、AWS 服务)
- 阶段:部署环境(dev、prod)
集成类型
| 类型 | 描述 |
|---|---|
| Lambda 代理 | 直通 Lambda(推荐) |
| Lambda 自定义 | 转换请求/响应 |
| HTTP 代理 | 直通 HTTP 端点 |
| AWS 服务 | 与 AWS 服务直接集成 |
| 模拟 | 返回静态响应 |
常见模式
使用 Lambda 创建 HTTP API
AWS CLI:
# Create HTTP API
aws apigatewayv2 create-api \
--name my-api \
--protocol-type HTTP \
--target arn:aws:lambda:us-east-1:123456789012:function:MyFunction
# Get API endpoint
aws apigatewayv2 get-api --api-id abc123 --query 'ApiEndpoint'
SAM 模板:
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: GET
使用 Lambda 代理创建 REST API
# Create REST API
aws apigateway create-rest-api \
--name my-rest-api \
--endpoint-configuration types=REGIONAL
API_ID=abc123
# Get root resource ID
ROOT_ID=$(aws apigateway get-resources --rest-api-id $API_ID --query 'items[0].id' --output text)
# Create resource
aws apigateway create-resource \
--rest-api-id $API_ID \
--parent-id $ROOT_ID \
--path-part items
RESOURCE_ID=xyz789
# Create method
aws apigateway put-method \
--rest-api-id $API_ID \
--resource-id $RESOURCE_ID \
--http-method GET \
--authorization-type NONE
# 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
# Deploy to stage
aws apigateway create-deployment \
--rest-api-id $API_ID \
--stage-name prod
API Gateway 的 Lambda 处理程序
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)
}
配置 CORS
HTTP API:
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:
# Enable CORS on resource
aws apigateway put-method \
--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}"}'
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
}'
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": "'\''*'\''"
}'
JWT 授权(HTTP API)
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 参考
HTTP API(apigatewayv2)
| 命令 | 描述 |
|---|---|
aws apigatewayv2 create-api | 创建 API |
aws apigatewayv2 get-apis | 列出 API |
aws apigatewayv2 create-route | 创建路由 |
aws apigatewayv2 create-integration | 创建集成 |
aws apigatewayv2 create-stage | 创建阶段 |
aws apigatewayv2 create-authorizer | 创建授权器 |
REST API(apigateway)
| 命令 | 描述 |
|---|---|
aws apigateway create-rest-api | 创建 API |
aws apigateway get-rest-apis | 列出 API |
aws apigateway create-resource | 创建资源 |
aws apigateway put-method | 创建方法 |
aws apigateway put-integration | 创建集成 |
aws apigateway create-deployment | 部署 API |
最佳实践
性能
- 简单用例请使用 HTTP API(成本低 70%,延迟更低)
- 为 REST API 启用缓存
- 除非需要全球分发,否则使用区域端点
- 为列表端点实现分页
安全
- 为所有端点启用授权
- 为 REST API 启用 WAF
- 使用 API 密钥进行速率限制(而非身份验证)
- 启用访问日志
- 仅使用 HTTPS
可靠性
- 设置节流以保护后端
- 适当配置超时
- 使用金丝雀部署进行更新
- 使用 CloudWatch 监控
故障排除
403 Forbidden
原因:
- 缺少授权
- API 密钥无效
- WAF 拦截
- 资源策略拒绝访问
调试:
# Check API key
aws apigateway get-api-key --api-key abc123 --include-value
# Check authorizer
aws apigatewayv2 get-authorizer --api-id abc123 --authorizer-id xyz789
502 Bad Gateway
原因:
- Lambda 错误
- 集成超时
- 响应格式无效
Lambda 响应格式:
# Correct format
return {
'statusCode': 200,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps({'message': 'success'})
}
# Wrong - missing statusCode
return {'message': 'success'}
504 Gateway Timeout
原因:
- 后端超时(REST API 的 Lambda 最长为 29 秒)
- 集成超时时间太短
解决方案:
- 增加 Lambda 超时时间
- 对长时间运行的操作使用异步处理
- 增加集成超时时间(REST 最长 29 秒,HTTP 最长 30 秒)
CORS 错误
调试:
- 检查 OPTIONS 方法是否存在
- 验证响应中的标头
- 检查来源是否与允许的来源匹配
参考资料
评论
支持 Markdown