api-gateway

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

AWS 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类型

TypeDescriptionUse Case
HTTP APILow-latency, cost-effectiveSimple APIs, Lambda proxy
REST APIFull-featured, more controlComplex APIs, transformation
WebSocket APIBidirectional communicationReal-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

集成类型

TypeDescription
Lambda ProxyPass-through to Lambda (recommended)
Lambda CustomTransform request/response
HTTP ProxyPass-through to HTTP endpoint
AWS ServiceDirect integration with AWS services
MockReturn 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
undefined
AWS CLI:
bash
undefined

Create 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
aws apigatewayv2 create-api
--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: GET
aws 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: GET

Create REST API with Lambda Proxy

创建带Lambda代理的REST API

bash
undefined
bash
undefined

Create REST API

Create REST API

aws apigateway create-rest-api
--name my-rest-api
--endpoint-configuration types=REGIONAL
API_ID=abc123
aws apigateway create-rest-api
--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
RESOURCE_ID=xyz789
aws apigateway create-resource
--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
aws apigateway put-method
--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
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

Deploy to stage

aws apigateway create-deployment
--rest-api-id $API_ID
--stage-name prod
undefined
aws apigateway create-deployment
--rest-api-id $API_ID
--stage-name prod
undefined

Lambda 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
undefined
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
undefined

Enable 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
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": "'''*'''" }'
undefined
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": "'''*'''" }'
undefined

JWT 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)

CommandDescription
aws apigatewayv2 create-api
Create API
aws apigatewayv2 get-apis
List APIs
aws apigatewayv2 create-route
Create route
aws apigatewayv2 create-integration
Create integration
aws apigatewayv2 create-stage
Create stage
aws apigatewayv2 create-authorizer
Create authorizer
命令描述
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)

REST API(apigateway)

CommandDescription
aws apigateway create-rest-api
Create API
aws apigateway get-rest-apis
List APIs
aws apigateway create-resource
Create resource
aws apigateway put-method
Create method
aws apigateway put-integration
Create integration
aws apigateway create-deployment
Deploy API
命令描述
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

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
undefined

Check 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
undefined
aws apigatewayv2 get-authorizer --api-id abc123 --authorizer-id xyz789
undefined

502 Bad Gateway

502 Bad Gateway错误

Causes:
  • Lambda error
  • Integration timeout
  • Invalid response format
Lambda response format:
python
undefined
可能原因:
  • Lambda函数执行出错
  • 集成超时
  • 响应格式无效
Lambda响应格式要求:
python
undefined

Correct 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'}
undefined
return {'message': 'success'}
undefined

504 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方法已配置
  • 验证响应头是否正确
  • 检查请求源是否在允许的源列表中

References

参考资料