如何在apigateway的cloudformation中自定义响应

时间:2017-02-06 19:00:19

标签: amazon-web-services templates aws-api-gateway amazon-cloudformation

我在用于cloudformation的apigateway模板中对GET方法进行了以下配置

      "paths": {
        "/customer/{customerid}": {
          "get": {
            "description": "Returns JSON customer objects from DynamoDB.",
            "parameters": [
              {
                "required": true,
                "type": "string",
                "name": "customerid",
                "in": "path"
              }
            ],
            "produces": [
              "application/json"
            ],
            "x-amazon-apigateway-integration": {
              "passthroughBehavior": "never",
              "responses": {
                "default": {
                  "statusCode": "200"
                }
              },
              "uri": {
                "Fn::Join": [
                  ":",
                  [
                    "arn",
                    "aws",
                    "apigateway",
                    {
                      "Ref": "AWS::Region"
                    },
                    "dynamodb",
                    "action/GetItem"
                  ]
                ]
              },
              "httpMethod": "POST",
              "requestTemplates": {
                "application/json": "{\n  \"TableName\": \"customer\",\n  \"Key\": {\n    \"customerid\": {\n      \"S\": \"$input.params('customerid')\"\n    }\n  }\n}\n"
              },
              "credentials": {
                "Fn::GetAtt": [
                  "TableAccessRole",
                  "Arn"
                ]
              },
              "type": "aws"
            },
            "consumes": [
              "application/json"
            ],
            "responses": {
              "200": {
                "description": "200 response"
              }
            }
          }
        }

api正在被完美地创建,然而,api的响应是

{
  "Item": {
    "Name": {
      "S": "Alex"
    },
    "CustomerId": {
      "S": "123"
    }
  }
}

但我希望这是一个简单的json,如

{
    "Name":"Alex",
    "CustomerId":"123"
}

我正在查看aws文档,但我无法确定需要更改配置的哪一部分。我知道我有input变量可以用来获取数据,但是我在哪里以及如何丢失

1 个答案:

答案 0 :(得分:0)

由于您的现有模板使用x-amazon-apigateway-integration Swagger extension,因此您可以将包含响应映射模板的responseTemplates对象添加到现有default response您&# 39;已经定义:

"x-amazon-apigateway-integration": {
  "passthroughBehavior": "never",
  "responses": {
    "default": {
      "statusCode": "200",
      "responseTemplates": {
        "application/json": "{\"Name\": \"$input.path('$.Item.Name.S')\", \"CustomerId\": \"$input.path('$.Item.CustomerId.S')\"}"
      }
    }
  },
  [...]