Menu
Amazon API Gateway
Developer Guide

API Gateway API Request and Response Payload-Mapping Template Reference

Amazon API Gateway defines a set of variables for working with models and mapping templates. This document describes those functions and provides examples for working with input payloads.

Accessing the $context Variable

The $context variable holds all the contextual information of your API call.

$context Variable Reference

ParameterDescription
$context.apiId

The identifier API Gateway assigns to your API.

$context.authorizer.principalId

The principal user identification associated with the token sent by the client.

$context.authorizer.claims.property

A property of the claims returned from the Amazon Cognito user pool after the method caller is successfully authenticated.

Note

Calling $context.authorizer.claims returns null.
$context.httpMethod

The HTTP method used. Valid values include: DELETE, GET, HEAD, OPTIONS, PATCH, POST, and PUT.

$context.identity.accountId

The AWS account ID associated with the request.

$context.identity.apiKey

The API owner key associated with your API.

$context.identity.caller

The principal identifier of the caller making the request.

$context.identity.cognitoAuthenticationProvider

The Amazon Cognito authentication provider used by the caller making the request. Available only if the request was signed with Amazon Cognito credentials.

For information related to this and the other Amazon Cognito $context variables, see Amazon Cognito Identity.

$context.identity.cognitoAuthenticationType

The Amazon Cognito authentication type of the caller making the request. Available only if the request was signed with Amazon Cognito credentials.

$context.identity.cognitoIdentityId

The Amazon Cognito identity ID of the caller making the request. Available only if the request was signed with Amazon Cognito credentials.

$context.identity.cognitoIdentityPoolId

The Amazon Cognito identity pool ID of the caller making the request. Available only if the request was signed with Amazon Cognito credentials.

$context.identity.sourceIp

The source IP address of the TCP connection making the request to API Gateway.

$context.identity.user

The principal identifier of the user making the request.

$context.identity.userAgent

The User Agent of the API caller.

$context.identity.userArn

The Amazon Resource Name (ARN) of the effective user identified after authentication.

$context.requestId

An automatically generated ID for the API call.

$context.resourceId

The identifier API Gateway assigns to your resource.

$context.resourcePath

The path to your resource. For more information, see Build an API Gateway API as an HTTP Proxy.

$context.stage

The deployment stage of the API call (for example, Beta or Prod).


Example

You may want to use the $context variable if you're using AWS Lambda as the target backend that the API method calls. For example, you may want to perform two different actions depending on whether the stage is in Beta or in Prod.

Context Variables Template Example

The following example shows how to get context variables:

{
    "stage" : "$context.stage",
    "request_id" : "$context.requestId",
    "api_id" : "$context.apiId",
    "resource_path" : "$context.resourcePath",
    "resource_id" : "$context.resourceId",
    "http_method" : "$context.httpMethod",
    "source_ip" : "$context.identity.sourceIp",
    "user-agent" : "$context.identity.userAgent",
    "account_id" : "$context.identity.accountId",
    "api_key" : "$context.identity.apiKey",
    "caller" : "$context.identity.caller",
    "user" : "$context.identity.user",
    "user_arn" : "$context.identity.userArn"
}

Accessing the $input Variable

The $input variable represents the input payload and parameters to be processed by your template. It provides four functions:

Function Reference

Variable and FunctionDescription
$input.body

Returns the raw payload as a string.

$input.json(x)

This function evaluates a JSONPath expression and returns the results as a JSON string.

For example, $input.json('$.pets') will return a JSON string representing the pets structure.

For more information about JSONPath, see JSONPath or JSONPath for Java.

$input.params()

Returns a map of all the request parameters of your API call.

$input.params(x)

Returns the value of a method request parameter from the path, query string, or header value (in that order) given a parameter name string x.

$input.path(x)

Takes a JSONPath expression string (x) and returns an object representation of the result. This allows you to access and manipulate elements of the payload natively in Apache Velocity Template Language (VTL).

For example, $input.path('$.pets').size()

For more information about JSONPath, see JSONPath or JSONPath for Java.


Examples

You may want to use the $input variable to get query strings and the request body with or without using models. You may also want to get the parameter and the payload, or a subsection of the payload, into your AWS Lambda function. The examples below show how to do this.

Example JSON Mapping Template

The following example shows how to use a mapping to read a name from the query string and then include the entire POST body in an element:

{
    "name" : "$input.params('name')",
    "body" : $input.json('$') 
}

If the JSON input contains unescaped characters that cannot be parsed by JavaScript, a 400 response may be returned. Applying $util.escapeJavaScript($input.json('$')) above will ensure that the JSON input can be parsed properly.

Example Inputs Mapping Template

The following example shows how to pass a JSONPath expression to the json() method. You could also read a specific property of your request body object by using a period (.), followed by your property name:

{
    "name" : "$input.params('name')",
    "body" : $input.json('$.mykey')  
}

If a method request payload contains unescaped characters that cannot be parsed by JavaScript, you may get 400 response. In this case, you need to call $util.escapeJavaScript() function in the mapping template, as shown as follows:

{
    "name" : "$input.params('name')",
    "body" : $util.escapeJavaScript($input.json('$.mykey')) 
}

Param Mapping Template Example

The following parameter-mapping example passes all parameters, including path, querystring and header, through to the integration endpoint via a JSON payload

#set($allParams = $input.params())
{
  "params" : {
    #foreach($type in $allParams.keySet())
    #set($params = $allParams.get($type))
    "$type" : {
      #foreach($paramName in $params.keySet())
      "$paramName" : "$util.escapeJavaScript($params.get($paramName))"
      #if($foreach.hasNext),#end
      #end
    }
    #if($foreach.hasNext),#end
    #end
  }
}

In effect, this mapping template outputs all the request parameters in the payload as outlined as follows:

{
  "parameters" : {
     "path" : {    
       "path_name" : "path_value", 
       ...
     }
     "header" : {  
       "header_name" : "header_value",
       ...
     }
     'querystring" : {
       "querystring_name" : "querystring_value",
       ...
     }
   }
}

Example Request and Response

Here’s an example that uses all three functions:

Request Template:

Resource: /things/{id}

With input template:
{
    "id" : "$input.params('id')",
    "count" : "$input.path('$.things').size()",
    "things" : $util.escapeJavaScript($input.json('$.things'))
}

POST /things/abc
{
    "things" : {
        "1" : {},
        "2" : {},
        "3" : {}
    }
}

Response:

{
  "id": "abc",
  "count": "3",
  "things": {
    "1": {},
    "2": {},
    "3": {}
  }
}

For more mapping examples, see Set Up Payload Mappings

Accessing the $stageVariables Variable

The syntax for inserting a stage variable looks like this: $stageVariables.

$stageVariables Reference

SyntaxDescription
$stageVariables.<variable_name>

<variable_name> represents a stage variable name.

$stageVariables['<variable_name>']

<variable_name> represents any stage variable name.

${stageVariables['<variable_name>']}

<variable_name> represents any stage variable name.


Accessing the $util Variable

The $util variable contains utility functions for use in mapping templates.

Note

Unless otherwise specified, the default character set is UTF-8.

$util Variable Reference

FunctionDescription
$util.escapeJavaScript()

Escapes the characters in a string using JavaScript string rules.

Note

This function will turn any regular single quotes (') into escaped ones (\'). However, the escaped single quotes are not valid in JSON. Thus, when the output from this function is used in a JSON property, you must turn any escaped single quotes (\') back to regular single quotes ('). This is shown in the following example:

 $util.escapeJavaScript(data).replaceAll("\'","'")
$util.parseJson()

Takes "stringified" JSON and returns an object representation of the result. You can use the result from this function to access and manipulate elements of the payload natively in Apache Velocity Template Language (VTL). For example, if you have the following payload:

{"errorMessage":"{\"key1\":\"var1\",\"key2\":{\"arr\":[1,2,3]}}"}

and use the following mapping template

#set ($errorMessageObj = $util.parseJson($input.path('$.errorMessage')))
{
   "errorMessageObjKey2ArrVal" : $errorMessageObj.key2.arr[0]
}

You will get the following output:

{
   "errorMessageObjKey2ArrVal" : 1
}
$util.urlEncode()

Converts a string into "application/x-www-form-urlencoded" format.

$util.urlDecode()

Decodes an "application/x-www-form-urlencoded" string.

$util.base64Encode()

Encodes the data into a base64-encoded string.

$util.base64Decode()

Decodes the data from a base64-encoded string.


Integration Passthrough Behaviors

When a method request carries a payload and either the Content-Type header does not match any specified mapping template or no mapping template is defined, you can choose to pass the client supplied request payload through the integration request to the back end without transformation. The process is known as integration passthrough. The actual passthrough behavior of an incoming request is determined by the option you choose for a specified mapping template, during integration request set-up, and the Content Type header that a client set in the incoming request. The following examples illustrate the possible passthrough behaviors.

Example 1: One mapping template is defined in the integration request for the application/json content type.

Content-Type header\Selected passthrough optionWHEN_NO_MATCHWHEN_NO_TEMPLATENEVER
None (default to application/jsonThe request payload is transformed using the template.The request payload is transformed using the template.The request payload is transformed using the template.
application/jsonThe request payload is transformed using the template.The request payload is transformed using the template.The request payload is transformed using the template.
application/xmlThe request payload is not transformed and is sent to the back end as-is.The request is rejected with an HTTP 415 Unsupported Media Type response.The request is rejected with an HTTP 415 Unsupported Media Type response.

Example 2: One mapping template is defined in the integration request for the application/xml content type.

Content-Type header\Selected passthrough optionWHEN_NO_MATCHWHEN_NO_TEMPLATENEVER
None (default to application/jsonThe request payload is not transformed and is sent to the back end as-is.The request is rejected with an HTTP 415 Unsupported Media Type response.The request is rejected with an HTTP 415 Unsupported Media Type response.
application/jsonThe request payload is not transformed and is sent to the back end as-is.The request is rejected with an HTTP 415 Unsupported Media Type response.The request is rejected with an HTTP 415 Unsupported Media Type response.
application/xmlThe request payload is transformed using the template.The request payload is transformed using the template.The request payload is transformed using the template.