Menu
Amazon API Gateway
Developer Guide

Map Method Request Data to Customize Gateway Responses

If API Gateway fails to process an incoming request, it returns to the client an error response without forwarding the request to the integration backend. By default, the error response contains a short descriptive error message. For example, if you attempt to call an operation on an undefined API resource, you receive an error response with the { "message": "Missing Authentication Token" } message. If you are new to API Gateway, you may find it difficult to understand what actually went wrong.

For some of the error responses, API Gateway allows customization by API developers to return the responses in different formats. For the Missing Authentication Token example, you can add a hint to the original response payload with the possible cause, as in this example: {"message":"Missing Authentication Token", "hint":"The HTTP method or resources may not be supported."}.

When your API mediates between an external exchange and the AWS cloud, you use VTL mapping templates for integration request or integration response to map the payload from one format to another. However, the VTL mapping templates work only for valid requests with successful responses. For invalid requests, API Gateway bypasses the integration altogether and returns an error response. You must use the customization to render the error responses in an exchange-compliant format. Here, the customization is rendered in a non-VTL mapping template supporting only simple variable substitutions.

Generalizing the API Gateway-generated error response to any responses generated by API Gateway, we refer to them as gateway responses. This distinguishes API Gateway-generated responses from the integration responses. A gateway response mapping template can access $context variable values and $stageVariables property values, as well as method request parameters, in the form of method.request.param-position.param-name. For more information about $context variables, see Accessing the $context Variable. For more information about $stageVariables, see Accessing the $stageVariables Variable. For more information about method request parameters, see Request parameters accessible by a mapping template.

API Gateway Responses

An API Gateway response is identified by a response type defined by API Gateway. The response consists of an HTTP status code, a set of additional headers that are specified by parameter mappings, and a payload that is generated by a non-VTL mapping template.

In the API Gateway REST API, a gateway response is represented by the GatewayResponse. In Swagger, a GatewayResponse instance is described by the x-amazon-apigateway-gateway-responses.gatewayResponse extension.

To enable a gateway response, you set up a gateway response for a supported response type at the API level. Whenever API Gateway returns a response of the type, the header mappings and payload mapping templates defined in the gateway response are applied to return the mapped results to the API caller.

In the following section, we show how to set up gateway responses using the API Gateway console and the API Gateway REST API.

Gateway Response Types Supported by API Gateway

API Gateway exposes the following gateway responses for customization by API developers.

Gateway response type Default status code Description
DEFAULT_4XX Null

The default gateway response for an unspecified response type with the status code of 4XX. Changing the status code of this fallback gateway response changes the status codes of all other 4XX responses to the new value. Resetting this status code to null reverts the status codes of all other 4XX responses to their original values.

DEFAULT_5XX Null

The default gateway response for an unspecified response type with a status code of 5XX. Changing the status code of this fallback gateway response changes the status codes of all other 5XX responses to the new value. Resetting this status code to null reverts the status codes of all other 5XX responses to their original values.

ACCESS_DENIED 403

The gateway response for authorization failure; for example, when access is denied by a custom or Amazon Cognito authorizer. If the response type is unspecified, this response defaults to the DEFAULT_4XX type.

API_CONFIGURATION_ERROR 500

The gateway response for invalid API configuration, including invalid endpoint address submitted, Base64 decoding failed on binary data when binary support is enacted, or integration response mapping cannot match any template and no default template is configured. If the response type is unspecified, this response defaults to the DEFAULT_5XX type.

AUTHORIZER_CONFIGURATION_ERROR 500

The gateway response for failing to connect to a custom or Amazon Cognito authorizer. If the response type is unspecified, this response defaults to the DEFAULT_5XX type.

AUTHORIZER_FAILURE 500

The gateway response when a custom or Amazon Cognito authorizer failed to authenticate the caller. If the response type is unspecified, this response defaults to the DEFAULT_5XX type.

BAD_REQUEST_PARAMETERS 400

The gateway response when the request parameter cannot be validated according to an enabled request validator. If the response type is unspecified, this response defaults to the DEFAULT_4XX type.

BAD_REQUEST_BODY 400

The gateway response when the request body cannot be validated according to an enabled request validator. If the response type is unspecified, this response defaults to the DEFAULT_4XX type.

EXPIRED_TOKEN 403

The gateway response for an AWS authentication token expired error. If the response type is unspecified, this response defaults to the DEFAULT_4XX type.

INTEGRATION_FAILURE 504

The gateway response for an integration failed error. If the response type is unspecified, this response defaults to the DEFAULT_5XX type.

INTEGRATION_TIMEOUT 504

The gateway response for an integration timed out error. If the response type is unspecified, this response defaults to the DEFAULT_5XX type.

INVALID_API_KEY 403

The gateway response for an invalid API key submitted for a method requiring an API key. If the response type is unspecified, this response defaults to the DEFAULT_4XX type.

INVALID_SIGNATURE 403

The gateway response for an invalid AWS signature error. If the response type is unspecified, this response defaults to the DEFAULT_4XX type.

MISSING_AUTHENTICATION_TOKEN 403

The gateway response for a missing authentication token error, including the cases when the client attempts to invoke an unsupported API method or resource. If the response type is unspecified, this response defaults to the DEFAULT_4XX type.

QUOTA_EXCEEDED 429

The gateway response for the usage plan quota exceeded error. If the response type is unspecified, this response defaults to the DEFAULT_4XX type.

REQUEST_TOO_LARGE 413

The gateway response for the request too large error. If the response type is unspecified, this response defaults to the DEFAULT_4XX type.

RESOURCE_NOT_FOUND 404

The gateway response when API Gateway cannot find the specified resource after an API request passes authentication and authorization, except for API key authentication and authorization. If the response type is unspecified, this response defaults to the DEFAULT_4XX type.

THROTTLED 429

The gateway response when usage plan-, method-, stage-, or account-level throttling limits exceeded. If the response type is unspecified, this response defaults to the DEFAULT_4XX type.

UNAUTHORIZED 401

The gateway response when the custom or Amazon Cognito authorizer failed to authenticate the caller.

UNSUPPORTED_MEDIA_TYPE 415

The gateway response when a payload is of an unsupported media type, if strict passthrough behavior is enabled. If the response type is unspecified, this response defaults to the DEFAULT_4XX type.

Use the API Gateway Console to Customize a Gateway Response

To customize a gateway response using the API Gateway console

  1. Sign in to the API Gateway console.

  2. Choose your existing API or create a new one.

  3. Expand the API in the primary navigation pane and choose Gateway Responses under the API.

  4. In the Gateway Responses pane, choose a response type. In this walkthrough, we use Missing Authentication Token (403) as an example.

  5. You can change the API Gateway-generated Status Code to return a different status code that meets your API's requirements.

  6. To return custom headers, choose Add Header under Response Headers. For illustration purposes, we add the following custom headers:

    Copy
    Access-Control-Allow-Origin:'a.b.c' x-request-id:method.request.header.Accept x-request-path:method.request.path.petId x-request-query:method.request.querystring.q

    In the preceding header mappings, a static domain name ('a.b.c') is mapped to the Allow-Control-Allow-Origin header to allow CORS access to the API; the input request header of x-amazn-RequestId is mapped to request-id in the response; the petId path variable of the incoming request is mapped to the request-path header in the response; and the q query parameter of the original request is mapped to the request-query header of the response.

  7. Under Body Mapping Templates, leave application/json for Content Type and type the following body mapping template in the Body Mapping Template editor:

    Copy
    { "message":"$context.error.messageString", "type": "$context.error.responseType", "statusCode": "'404'", "stage": "$context.stage", "resourcePath": "$context.resourcePath", "stageVariables.a": "$stageVariables.a" }

    This example shows how to map $context and $stageVariables properties to properties of the gateway response body.

  8. Choose Save.

  9. Deploy the API to a new or existing stage.

  10. Test it by calling the following CURL command:

    Copy
    curl -v https://o81lxisefl.execute-api.us-east-1.amazonaws.com/custErr/pets/5/type?q=1

    You should get a gateway response similar to the following:

    Copy
    > GET /custErr/pets/5/type?q=1 HTTP/1.1 Host: o81lxisefl.execute-api.us-east-1.amazonaws.com User-Agent: curl/7.51.0 Accept: */* HTTP/1.1 404 Not Found Content-Type: application/json Content-Length: 334 Connection: keep-alive Date: Tue, 02 May 2017 03:15:47 GMT x-amzn-RequestId: a2be05a4-2ee5-11e7-bbf2-df131ec50ae6 Access-Control-Allow-Origin: a.b.c x-amzn-ErrorType: MissingAuthenticationTokenException header-1: static x-request-query: 1 x-request-path: X-Cache: Error from cloudfront Via: 1.1 441811a054e8d055b893175754efd0c3.cloudfront.net (CloudFront) X-Amz-Cf-Id: nNDR-fX4csbRoAgtQJ16u0rTDz9FZWT-Mk93KgoxnfzDlTUh3flmzA== { "message":"Missing Authentication Token", "type": MISSING_AUTHENTICATION_TOKEN, "statusCode": '404', "stage": custErr, "resourcePath": , "stageVariables.a": a }

    The preceding example assumes that the API backend is Pet Store and the API has a stage variable, a, defined.

Use the API Gateway REST API to Customize a Gateway Response

Before customizing a gateway response using the API Gateway REST API, you must have already created an API and have obtained its identifier. To retrieve the API identifier, you can follow restapi:gateway-responses link relation and examine the result.

To customize a gateway response using the API Gateway REST API

  1. To overwrite an entire GatewayResponse instance, call the gatewayresponse:put action, specifying a desired responseType in the URL path parameter and supplying in the request payload the statusCode, responseParameters and responseTemplates mappings.

  2. To update part of a GatewayResponse instance, call the gatewayresponse:update action, specifying a desired responseType in the URL path parameter and supplying in the request payload desired individual GatewayResponse properties, for example, the responseParameters or the responseTemplates mapping.

Set up Gateway Response Customization in Swagger

You can use the x-amazon-apigateway-gateway-responses extension at the API root level to customize gateway responses in Swagger. The following Swagger definition shows an example for customizing the GatewayResponse of the MISSING_AUTHENTICATION_TOKEN type.

Copy
"x-amazon-apigateway-gateway-responses": { "MISSING_AUTHENTICATION_TOKEN": { "statusCode": 404, "responseParameters": { "gatewayresponse.header.x-request-path": "method.input.params.petId", "gatewayresponse.header.x-request-query": "method.input.params.q", "gatewayresponse.header.Access-Control-Allow-Origin": "'a.b.c'", "gatewayresponse.header.x-request-header": "method.input.params.Accept" }, "responseTemplates": { "application/json": "{\n \"message\": $context.error.messageString,\n \"type\": \"$context.error.responseType\",\n \"stage\": \"$context.stage\",\n \"resourcePath\": \"$context.resourcePath\",\n \"stageVariables.a\": \"$stageVariables.a\",\n \"statusCode\": \"'404'\"\n}" } }

In this example, the customization changes the status code from the default (403) to 404. It also adds to the gateway response four header parameters and one body mapping template for the application/json media type.