AWS Mock Integration with Dynamic Status Code

时间:2018-02-26 17:53:26

标签: amazon-web-services aws-api-gateway swagger-2.0

I'm using a swagger/OpenAPI file to describe a mock API that I've implemented in AWS API Gateway. The API returns a HTTP 200 when the swagger is written like this:

"x-amazon-apigateway-request-validator": "params-only",
"x-amazon-apigateway-integration": {
    "requestTemplates": {
        "application/json" : "{\"statusCode\": 200 }"
    },
    "responses" : {
        "2\\d{2}" : {
            "statusCode" : "200"
        },
        "4\\d{2}" : {
            "statusCode" : "400"
        }
    },
    "passthroughBehavior": "when_no_match",
    "timeoutInMillis": "20000",
    "httpMethod": "POST",
    "type": "mock"
}

However, when I alter the swagger to return a value found in the request header, I get a HTTP 500 error. Here's the modified swagger:

"x-amazon-apigateway-request-validator": "params-only",
"x-amazon-apigateway-integration": {
    "requestTemplates": {
        "application/json" : "{\"statusCode\": 200 }"
    },
    "responses" : {
        "2\\d{2}" : {
            "statusCode" : "$input.params('Mock-Return-Code')"
        },
        "4\\d{2}" : {
            "statusCode" : "$input.params('Mock-Return-Code')"
        }
    },
    "passthroughBehavior": "when_no_match",
    "timeoutInMillis": "20000",
    "httpMethod": "POST",
    "type": "mock"
}

Here's the exact error I receive when I run the API with the $input.params reference:

Execution failed due to configuration error: Output mapping refers to an invalid method response: $input.params('Mock-Return-Code')

Any ideas?

1 个答案:

答案 0 :(得分:1)

我发现我是以错误的方式解决这个问题。我应该一直在调整请求模板,而不是调整响应模板。这是我工作的一个例子。

首先,我必须更新路径参数,以便声明可选的标题。

"get": {
    "parameters": [
        {
            "name": "x-mock-response-code",
            "in": "header",
            "required": false,
            "type": "string",
            "default": "200"
        }
    ]
}

接下来,我修改了API Gateway Integrations以使用标头值来确定要返回的响应模板。

"x-amazon-apigateway-request-validator": "params-only",
"x-amazon-apigateway-integration": {
    "requestTemplates": {
        "application/json": "#set($rc = $input.params('x-mock-response-code'))\r\n\r\n#if($rc.length() != 0)\r\n {\r\n \"statusCode\" : $rc\r\n }\r\n#else\r\n {\r\n \"statusCode\" : 200\r\n }\r\n#end"
    },
    "requestParameters" : {
        "integration.request.header.x-mock-response-code" : "method.request.header.x-mock-response-code"
    },
    "responses" : {
        "2\\d{2}" : {
            "statusCode" : "200"
        },
        "4\\d{2}" : {
            "statusCode" : "400"
        }
    },
    "passthroughBehavior": "when_no_match",
    "timeoutInMillis": "20000",
    "httpMethod": "POST",
    "type": "mock"
}

以下显示了漂亮格式的JSON请求模板代码:

#set($rc = $input.params('x-mock-response-code'))

#if($rc.length() != 0)
{
    "statusCode" : $rc
}
#else
{
    "statusCode" : 200
}
#end