

# Gateway responses for REST APIs in API Gateway
Gateway responses

 A gateway response is identified by a response type that is 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](https://velocity.apache.org/engine/devel/vtl-reference.html) mapping template. 

 In the API Gateway REST API, a gateway response is represented by the [GatewayResponse](https://docs.aws.amazon.com/apigateway/latest/api/API_GatewayResponse.html). In OpenAPI, a `GatewayResponse` instance is described by the [x-amazon-apigateway-gateway-responses.gatewayResponse](api-gateway-swagger-extensions-gateway-responses.gatewayResponse.md) extension. 

To enable a gateway response, you set up a gateway response for a [supported response type](supported-gateway-response-types.md) at the API level. Whenever API Gateway returns a response of this 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 by using the API Gateway console and the API Gateway REST API. 

## Setting up gateway responses to customize error 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 [Context variables for data transformations](api-gateway-mapping-template-reference.md#context-variable-reference). For more information about `$stageVariables`, see [Stage variables](api-gateway-mapping-template-reference.md#stagevariables-template-reference). For more information about method request parameters, see [Input variables](api-gateway-mapping-template-reference.md#input-variable-reference).

**Topics**
+ [

## Setting up gateway responses to customize error responses
](#customize-gateway-responses)
+ [

# Set up a gateway response for a REST API using the API Gateway console
](set-up-gateway-response-using-the-console.md)
+ [

# Set up a gateway response using the API Gateway REST API
](set-up-gateway-response-using-the-api.md)
+ [

# Set up gateway response customization in OpenAPI
](set-up-gateway-responses-in-swagger.md)
+ [

# Gateway response types for API Gateway
](supported-gateway-response-types.md)

# Set up a gateway response for a REST API using the API Gateway console


The following example shows how to set up a gateway response for a REST API using the API Gateway console 

**To customize a gateway response using the API Gateway console**

1. Sign in to the API Gateway console at [https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway).

1. Choose a REST API.

1. In the main navigation pane, choose **Gateway responses**.

1. Choose a response type, and then choose **Edit**. In this walkthrough, we use **Missing authentication token** as an example. 

1. You can change the API Gateway-generated **Status code** to return a different status code that meets your API's requirements. In this example, the customization changes the status code from the default (`403`) to `404` because this error message occurs when a client calls an unsupported or invalid resource that can be thought of as not found.

1. To return custom headers, choose **Add response header** under **Response headers**. For illustration purposes, we add the following custom headers: 

   ```
   Access-Control-Allow-Origin:'a.b.c'
   x-request-id:method.request.header.x-amzn-RequestId
   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-amzn-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.

1. Under **Response templates**, keep `application/json` for **Content Type** and enter the following body mapping template in the **Template body** editor:

   ```
   {
        "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.

1. Choose **Save changes**.

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

Test your gateway response by calling the following CURL command, assuming the corresponding API method's invoke URL is `https://o81lxisefl.execute-api.us-east-1.amazonaws.com/custErr/pets/{petId}`:

```
curl -v -H 'x-amzn-RequestId:123344566' https://o81lxisefl.execute-api.us-east-1.amazonaws.com/custErr/pets/5/type?q=1
```

Because the extra query string parameter `q=1` isn't compatible with the API, an error is returned from the specified gateway response. You should get a gateway response similar to the following:

```
> GET /custErr/pets/5?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: 123344566
Access-Control-Allow-Origin: a.b.c
x-amzn-ErrorType: MissingAuthenticationTokenException
header-1: static
x-request-query: 1
x-request-path: 5
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": /pets/{petId},
     "stageVariables.a": a
}
```

The preceding example assumes that the API backend is [Pet Store](http://petstore-demo-endpoint.execute-api.com/petstore/pets) and the API has a stage variable, `a`, defined.

# Set up a gateway response using the API Gateway REST API


 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](https://docs.aws.amazon.com/apigateway/latest/api/API_GetGatewayResponses.html) link relation and examine the result. 

**To customize a gateway response using the API Gateway REST API**

1. To overwrite an entire [GatewayResponse](https://docs.aws.amazon.com/apigateway/latest/api/API_GatewayResponse.html) instance, call the [gatewayresponse:put](https://docs.aws.amazon.com/apigateway/latest/api/API_PutGatewayResponse.html) action. Specify a desired [responseType](https://docs.aws.amazon.com/apigateway/latest/api/API_GatewayResponse.html#responseType) in the URL path parameter, and supply in the request payload the [statusCode](https://docs.aws.amazon.com/apigateway/latest/api/API_GatewayResponse.html#statusCode), [responseParameters](https://docs.aws.amazon.com/apigateway/latest/api/API_GatewayResponse.html#responseParameters), and [responseTemplates](https://docs.aws.amazon.com/apigateway/latest/api/API_GatewayResponse.html#responseTemplates) mappings.

1. To update part of a `GatewayResponse` instance, call the [gatewayresponse:update](https://docs.aws.amazon.com/apigateway/latest/api/API_UpdateGatewayResponse.html) action. Specify a desired `responseType` in the URL path parameter, and supply in the request payload the individual `GatewayResponse` properties you want—for example, the `responseParameters` or the `responseTemplates` mapping.

# Set up gateway response customization in OpenAPI


 You can use the `x-amazon-apigateway-gateway-responses` extension at the API root level to customize gateway responses in OpenAPI. The following OpenAPI definition shows an example for customizing the [GatewayResponse](https://docs.aws.amazon.com/apigateway/latest/api/API_GatewayResponse.html) of the `MISSING_AUTHENTICATION_TOKEN` type. 

```
  "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.

# Gateway response types for API Gateway


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


| Gateway response type | Default status code | Description | 
| --- | --- | --- | 
| ACCESS\$1DENIED | 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\$1CONFIGURATION\$1ERROR | 500 | The gateway response for an invalid API configuration—including when an invalid endpoint address is submitted, when base64 decoding fails on binary data when binary support is enacted, or when integration response mapping can't match any template and no default template is configured. If the response type is unspecified, this response defaults to the `DEFAULT_5XX` type. | 
| AUTHORIZER\$1CONFIGURATION\$1ERROR | 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\$1FAILURE | 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\$1REQUEST\$1PARAMETERS | 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\$1REQUEST\$1BODY | 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. | 
| DEFAULT\$14XX |  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.  [AWS WAF custom responses](https://docs.aws.amazon.com/waf/latest/developerguide/waf-custom-request-response.html) take precedence over custom gateway responses.   | 
| DEFAULT\$15XX | 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. | 
| EXPIRED\$1TOKEN | 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\$1FAILURE | 504 | The gateway response for an integration failed error. If the response type is unspecified, this response defaults to the `DEFAULT_5XX` type. | 
| INTEGRATION\$1TIMEOUT | 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\$1API\$1KEY | 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\$1SIGNATURE | 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\$1AUTHENTICATION\$1TOKEN | 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\$1EXCEEDED | 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\$1TOO\$1LARGE | 413 | The gateway response for the request too large error. If the response type is unspecified, this response defaults to: `HTTP content length exceeded 10485760 bytes`. | 
| RESOURCE\$1NOT\$1FOUND | 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\$1MEDIA\$1TYPE | 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. | 
| WAF\$1FILTERED | 403 | The gateway response when a request is blocked by AWS WAF. If the response type is unspecified, this response defaults to the `DEFAULT_4XX` type.  [AWS WAF custom responses](https://docs.aws.amazon.com/waf/latest/developerguide/waf-custom-request-response.html) take precedence over custom gateway responses.   | 