AWS API Gateway Responses

Nick Gibbon
Pareture
Published in
2 min readMay 16, 2019

--

Terraform for AWS API GW Gateway Error Responses

AWS API Gateway manages a selection of issues at the Gateway layer. These are things like returning 404s for none-existent resources or a 403 if the API is configured to use API keys and one is not provided by the consumer.

These are called ‘Gateway Responses’. There is a definitive list in the doc below and they can be found in the console (AWS/APIGW/APIs/{api}/Gateway Responses).

By default they are set very basically as can be seen above.

#mapping template
{"message":$context.error.messageString}

Which results in the following output for an invalid API Key for example

{
"message": "Forbidden"
}

Users can configure the default Gateway Responses so that responses are more informative or so that they align with the error formatting returned from the backend.

This is done by adjusting the mapping template. Values can be hardcoded or generated dynamically from a set of context variables:

For example the below terraform can be used to adjust the 403 Invalid API Key Response.

resource "aws_api_gateway_gateway_response" "gateway-response" {
rest_api_id = "${aws_api_gateway_rest_api.api.id}"
status_code = "403"
response_type = "INVALID_API_KEY"
response_templates = {
"application/json" =
"{\"status\":403,\"layer\":\"Gateway\",\"request-id\":\"$context.requestId\",\"code\":\"$context.error.responseType\",\"message\":\"$context.error.message\"}"
}
}

And the result is a new and improved Gateway Response!

{
"status": 403,
"layer": "Gateway",
"request-id": "684f8c4c-7819-11e9-b437-5b5b1b183784",
"code": "INVALID_API_KEY",
"message": "Forbidden"
}

More resources

Terraform AWS APIGW Gateway Response doc:

https://www.terraform.io/docs/providers/aws/r/api_gateway_gateway_response.html

Gateway Responses AWS docs section:

https://docs.aws.amazon.com/apigateway/latest/developerguide/customize-gateway-responses.html

--

--

Nick Gibbon
Pareture

Software reliability engineer & manager in cloud infrastructure, platforms & tools.