跳至内容

如何使用 API Gateway 作为其他 AWS 服务的代理?

4 分钟阅读
0

我想使用 Amazon API Gateway 作为其他 AWS 服务的代理,并将其他服务与 API Gateway 集成。

解决方法

AWS 服务 API 是 REST API,您可以向其发出 HTTPS 请求。要将其他服务与 API Gateway 进行集成,请构建从 API Gateway 到服务 API 的 HTTPS 请求。

使用 AWS 服务配置 API Gateway REST API

以下示例将 Amazon Simple Notification Service (Amazon SNS) Publish API 与 API Gateway 进行集成:

  1. 创建 Amazon SNS 主题并记下该主题的 Amazon 资源名称 (ARN)。
  2. 为主题创建订阅
  3. 使用 AWS Identity and Access Management (IAM) 控制台创建 AWS 服务代理执行角色
    注意: 对于 Amazon SNS 示例配置,请使用 sns:Publish API 操作。
  4. 创建 REST API
  5. 要导入 REST API,请使用以下示例 OpenAPI 2.0 定义模板:
    {
      "swagger": "2.0",
      "info": {
        "version": "2019-10-09T14:10:24Z",
        "title": "aws-service-integration"
      },
      "basePath": "/dev",
      "schemes": [
        "https"
      ],
      "paths": {
        "/test": {
          "post": {
            "produces": [
              "application/json"
            ],
            "parameters": [
              {
                "name": "Message",
                "in": "query",
                "required": true,
                "type": "string"
              },
              {
                "name": "TopicArn",
                "in": "query",
                "required": true,
                "type": "string"
              }
            ],
            "responses": {
              "200": {
                "description": "200 response",
                "schema": {
                  "$ref": "#/definitions/Empty"
                }
              }
            },
            "x-amazon-apigateway-request-validator": "Validate body, query string parameters, and headers",
            "x-amazon-apigateway-integration": {
              "credentials": "arn:aws:iam::account-id:role/apigateway-sns-role",
              "uri": "arn:aws:apigateway:your-region:sns:action/Publish",
              "responses": {
                "default": {
                  "statusCode": "200"
                }
              },
              "requestParameters": {
                "integration.request.header.Content-Type": "'application/x-www-form-urlencoded'",
                "integration.request.querystring.Message": "method.request.querystring.Message",
                "integration.request.querystring.TopicArn": "method.request.querystring.TopicArn"
              },
              "requestTemplates": {
                "application/json": "Action=Publish&TopicArn=$util.urlEncode(*YOUR-TOPIC-ARN*)&Message=$util.urlEncode($input.params('Message'))"
              },
              "passthroughBehavior": "when_no_match",
              "httpMethod": "POST",
              "type": "aws"
            }
          }
        }
      },
      "definitions": {
        "Empty": {
          "type": "object",
          "title": "Empty Schema"
        }
      },
      "x-amazon-apigateway-request-validators": {
        "Validate body, query string parameters, and headers": {
          "validateRequestBody": true,
          "validateRequestParameters": true
        }
      }
    }
    注意:arn:aws:iam::account-id:role/apigateway-sns-role 替换为您的 IAM 角色的 ARN,将 YOUR-TOPIC-ARN 替换为您的 SNS 主题的 ARN,将 your-region 替换为您的 AWS 区域。
    上述模板为您的 API Gateway API 创建方法、方法请求参数以及集成请求参数。
  6. (可选)要测试 API,请运行以下 curl 命令:
    curl -X POST 'YOUR-API-URL/stage/resource-path?Message=hello&TopicArn=YOUR-TOPIC-ARN'
    注意:YOUR-API-URL 替换为您的 API URL,将 YOUR-TOPIC-ARN 替换为您的 SNS 主题的 ARN。

有关详细信息,请参阅教程: 利用 AWS 集成创建 REST API

从服务 API 获取 HTTPS 请求

注意: 如果在运行 AWS 命令行界面 (AWS CLI) 命令时收到错误,请参阅 AWS CLI 错误故障排除。此外,请确保您使用的是最新版本的 AWS CLI

要从 API 调用获取 HTTPS 请求,请运行以下 publish 命令:

aws sns publish --topic-arn arn:aws:sns:us-east-1:123456789012:test --message "hi" --debug

注意:arn:aws:sns:us-east-1:123456789012:test 替换为您的 Amazon SNS 主题的 ARN。

Amazon SNS 配置的输出示例:

2018-11-22 11:56:39,647 - MainThread - botocore.client - DEBUG - Registering retry handlers for service: sns
2018-11-22 11:56:39,648 - MainThread - botocore.hooks - DEBUG - Event before-parameter-build.sns.Publish: calling handler <function generate_idempotent_uuid at 0x11093d320>
2018-11-22 11:56:39,649 - MainThread - botocore.endpoint - DEBUG - Making request for OperationModel(name=Publish) (verify_ssl=True) with params: {'body': {'Action': u'Publish', u'Message': u'hello', 'Version': u'2010-03-31', u'TopicArn': u'arn:aws:sns:us-east-1:123456789012:test'}, 'url': u'https://sns.us-east-1.amazonaws.com/', 'headers': {'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8', 'User-Agent': 'aws-cli/1.15.74 Python/2.7.14 Darwin/16.7.0 botocore/1.9.23'}, 'context': {'auth_type': None, 'client_region': 'us-east-1', 'has_streaming_input': False, 'client_config': <botocore.config.Config object at 0x1118437d0>}, 'query_string': '', 'url_path': '/', 'method': u'POST'}
2018-11-22 11:56:39,650 - MainThread - botocore.hooks - DEBUG - Event request-created.sns.Publish: calling handler <bound method RequestSigner.handler of <botocore.signers.RequestSigner object at 0x111843750>>
2018-11-22 11:56:39,650 - MainThread - botocore.hooks - DEBUG - Event choose-signer.sns.Publish: calling handler <function set_operation_specific_signer at 0x11093d230>
2018-11-22 11:56:39,650 - MainThread - botocore.auth - DEBUG - Calculating signature using v4 auth.
2018-11-22 11:56:39,651 - MainThread - botocore.auth - DEBUG - CanonicalRequest:
POST
/
content-type:application/x-www-form-urlencoded; charset=utf-8
host:sns.us-east-1.amazonaws.com
x-amz-date:20181122T062639Z
content-type;host;x-amz-date

输出包含 HTTPS 请求、传递的标头,该请求为 POST HTTP 方法。

(可选)检查集成配置

要验证您的集成设置配置是否正确,请运行以下 get-integration 命令:

aws apigateway get-integration --rest-api-id 1234123412 --resource-id y9h6rt --http-method POST

Amazon SNS 配置的输出示例:

{
  "type": "AWS",
  "httpMethod": "POST",
  "uri": "arn:aws:apigateway:eu-north-1:sns:action/Publish",
  "credentials": "arn:aws:iam::123456789:role/apigateway-sns-role",
  "requestParameters": {
    "integration.request.header.Content-Type": "'application/x-www-form-urlencoded'",
    "integration.request.querystring.Message": "method.request.querystring.Message",
    "integration.request.querystring.TopicArn": "method.request.querystring.TopicArn"
  },
  "requestTemplates": {
    "application/json": "Action=Publish&TopicArn=$util.urlEncode('arn:aws:sns:eu-north-1:123456789:test-standard')&Message=$util.urlEncode($input.params('Message'))"
  },
  "passthroughBehavior": "WHEN_NO_MATCH",
  "timeoutInMillis": 29000,
  "cacheNamespace": "v2e7yo",
  "cacheKeyParameters": [],
  "integrationResponses": {
    "200": {
      "statusCode": "200"
    }
  },
  "responseTransferMode": "BUFFERED"
}

要获得更大的消息有效载荷,请在您的 API 上运行以下 Amazon SNS 集成:

"requestParameters": {
  "integration.request.header.Content-Type": "'application/x-www-form-urlencoded'"
},
"requestTemplates": {
  "application/json": "Action=Publish&TopicArn=$util.urlEncode('*YOUR-TOPIC-ARN*')&Message=$util.urlEncode($input.body)"
}

注意:YOUR-TOPIC-ARN 替换为您的 SNS 主题的 ARN。

Amazon SNS 支持的最大标头大小为 16KB。在向集成发送请求之前,使用请求映射模板将传入的 HTTP 请求转换为其他格式。由于 Amazon SNS 主题 ARN 是硬编码到映射模板中的,因此客户不会在请求中传递 SNS 主题 ARN。

相关信息

API Gateway 中用于 REST API 的方法

API Gateway 中 REST API 的集成

API Gateway 中 REST API 的参数映射示例

AWS 官方已更新 6 个月前