API Gateway mapping template and access logging variable reference
This section provides reference information for the variables and functions that Amazon API Gateway defines for use with data models, authorizers, mapping templates, and CloudWatch access logging. For detailed information about how to use these variables and functions, see Understanding mapping templates.
Topics
Note
For $method
and $integration
variables, see Amazon API Gateway API request and response data
mapping reference.
$context
Variables for data
models, authorizers, mapping templates, and CloudWatch access logging
The following $context
variables can be used in data models, authorizers,
mapping templates, and CloudWatch access logging.
For $context
variables that can be used only in CloudWatch access logging, see
$context
Variables for access logging only.
Parameter | Description |
---|---|
$context.accountId |
The API owner's AWS account ID. |
$context.apiId |
The identifier API Gateway assigns to your API. |
$context.authorizer.claims. |
A property of the claims returned from the Amazon Cognito user pool after the method caller is successfully authenticated. For more information, see Control access to a REST API using Amazon Cognito user pools as authorizer. NoteCalling |
$context.authorizer.principalId |
The principal user identification associated with the token sent by the client and returned from an API Gateway Lambda authorizer (formerly known as a custom authorizer). For more information, see Use API Gateway Lambda authorizers. |
$context.authorizer. |
The stringified value of the specified key-value pair of the
calling For more information, see Use API Gateway Lambda authorizers. |
$context.awsEndpointRequestId |
The AWS endpoint's request ID. |
$context.domainName |
The full domain name used to invoke the API. This should be the
same as the incoming |
$context.domainPrefix |
The first label of the |
$context.error.message |
A string containing an API Gateway error message. This variable can only be used for simple variable substitution in a GatewayResponse body-mapping template, which is not processed by the Velocity Template Language engine, and in access logging. For more information, see Monitoring WebSocket API execution with CloudWatch metrics and Setting up gateway responses to customize error responses. |
$context.error.messageString |
The quoted value of $context.error.message , namely
"$context.error.message" . |
$context.error.responseType |
A type of GatewayResponse. This variable can only be used for simple variable substitution in a GatewayResponse body-mapping template, which is not processed by the Velocity Template Language engine, and in access logging. For more information, see Monitoring WebSocket API execution with CloudWatch metrics and Setting up gateway responses to customize error responses. |
$context.error.validationErrorString |
A string containing a detailed validation error message. |
$context.extendedRequestId |
The extended ID that API Gateway generates and assigns to the API request. The extended request ID contains useful information for debugging and troubleshooting. |
$context.httpMethod |
The HTTP method used. Valid values include: |
$context.identity.accountId |
The AWS account ID associated with the request. |
$context.identity.apiKey |
For API methods that require an API key, this variable is the API key associated with the method request. For methods that don't require an API key, this variable is null. For more information, see Creating and using usage plans with API keys. |
$context.identity.apiKeyId |
The API key ID associated with an API request that requires an API key. |
$context.identity.caller |
The principal identifier of the caller that signed the request. Supported for resources that use IAM authorization. |
$context.identity.cognitoAuthenticationProvider |
A comma-separated list of the Amazon Cognito authentication providers used by the caller making the request. Available only if the request was signed with Amazon Cognito credentials. For example, for an identity from an Amazon Cognito user pool, For information, see Using Federated Identities in the Amazon Cognito Developer Guide. |
$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. Possible values include |
$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.principalOrgId |
The AWS organization ID. |
$context.identity.sourceIp |
The source IP address of the immediate TCP connection making the request to API Gateway endpoint. |
$context.identity.clientCert.clientCertPem |
The PEM-encoded client certificate that the client presented during mutual TLS authentication. Present when a client accesses an API by using a custom domain name that has mutual TLS enabled. Present only in access logs if mutual TLS authentication fails. |
$context.identity.clientCert.subjectDN |
The distinguished name of the subject of the certificate that a client presents. Present when a client accesses an API by using a custom domain name that has mutual TLS enabled. Present only in access logs if mutual TLS authentication fails. |
$context.identity.clientCert.issuerDN |
The distinguished name of the issuer of the certificate that a client presents. Present when a client accesses an API by using a custom domain name that has mutual TLS enabled. Present only in access logs if mutual TLS authentication fails. |
$context.identity.clientCert.serialNumber |
The serial number of the certificate. Present when a client accesses an API by using a custom domain name that has mutual TLS enabled. Present only in access logs if mutual TLS authentication fails. |
$context.identity.clientCert.validity.notBefore |
The date before which the certificate is invalid. Present when a client accesses an API by using a custom domain name that has mutual TLS enabled. Present only in access logs if mutual TLS authentication fails. |
$context.identity.clientCert.validity.notAfter |
The date after which the certificate is invalid. Present when a client accesses an API by using a custom domain name that has mutual TLS enabled. Present only in access logs if mutual TLS authentication fails. |
$context.identity.user |
The principal identifier of the user that will be authorized against resource access. Supported for resources that use IAM authorization. |
$context.identity.userAgent |
The |
$context.identity.userArn |
The Amazon Resource Name (ARN) of the effective user identified after authentication. For more information, see https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html. |
$context.path |
The request path. For example, for a non-proxy request URL of
https://{rest-api-id}.execute-api.{region}.amazonaws.com/{stage}/root/child ,
the $context.path value is
/{stage}/root/child . |
$context.protocol |
The request protocol, for example, HTTP/1.1 .
NoteAPI Gateway APIs can accept HTTP/2 requests, but API Gateway sends requests to backend integrations using HTTP/1.1. As a result, the request protocol is logged as HTTP/1.1 even if a client sends a request that uses HTTP/2. |
$context.requestId |
An ID for the request. Clients can override this request ID.
Use |
$context.requestOverride.header. |
The request header override. If this parameter is defined, it contains the headers to be used instead of the HTTP Headers that are defined in the Integration Request pane. For more information, see Use a mapping template to override an API's request and response parameters and status codes. |
$context.requestOverride.path. |
The request path override. If this parameter is defined, it contains the request path to be used instead of the URL Path Parameters that are defined in the Integration Request pane. For more information, see Use a mapping template to override an API's request and response parameters and status codes. |
$context.requestOverride.querystring. |
The request query string override. If this parameter is defined, it contains the request query strings to be used instead of the URL Query String Parameters that are defined in the Integration Request pane. For more information, see Use a mapping template to override an API's request and response parameters and status codes. |
$context.responseOverride.header. |
The response header override. If this parameter is defined, it contains the header to be returned instead of the Response header that is defined as the Default mapping in the Integration Response pane. For more information, see Use a mapping template to override an API's request and response parameters and status codes. |
$context.responseOverride.status |
The response status code override. If this parameter is defined, it contains the status code to be returned instead of the Method response status that is defined as the Default mapping in the Integration Response pane. For more information, see Use a mapping template to override an API's request and response parameters and status codes. |
$context.requestTime |
The CLFdd/MMM/yyyy:HH:mm:ss
+-hhmm ). |
$context.requestTimeEpoch |
The Epoch |
$context.resourceId |
The identifier that API Gateway assigns to your resource. |
$context.resourcePath |
The path to your resource. For example, for the non-proxy request
URI of
|
$context.stage |
The deployment stage of the API request (for example,
|
$context.wafResponseCode |
The response received from AWS WAF:
|
$context.webaclArn |
The complete ARN of the web ACL that is used to decide whether to allow or block the request. Will not be set if the stage is not associated with a web ACL. For more information, see Using AWS WAF to protect your APIs. |
$context
Variable
template example
You might want to use $context
variables in a mapping template if your API
method passes structured data to a backend that requires the data to be in a particular
format.
The following example shows a mapping template that maps incoming
$context
variables to backend variables with slightly different names
in an integration request payload:
Note
Note that one of the variables is an API key. This example assumes that the method has "require API key" enabled.
{ "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" }
$context
Variables for access logging only
The following $context
variables are available only for access logging.
For more information, see Setting up CloudWatch logging for a REST API in API Gateway. (For WebSocket APIs, see
Monitoring WebSocket API execution
with CloudWatch metrics.)
Parameter | Description |
---|---|
$context.authorize.error |
The authorization error message. |
$context.authorize.latency |
The authorization latency in ms. |
$context.authorize.status |
The status code returned from an authorization attempt. |
$context.authorizer.error |
The error message returned from an authorizer. |
$context.authorizer.integrationLatency |
The authorizer latency in ms. |
$context.authorizer.integrationStatus |
The status code returned from a Lambda authorizer. |
$context.authorizer.latency |
The authorizer latency in ms. |
$context.authorizer.requestId |
The AWS endpoint's request ID. |
$context.authorizer.status |
The status code returned from an authorizer. |
$context.authenticate.error |
The error message returned from an authentication attempt. |
$context.authenticate.latency |
The authentication latency in ms. |
$context.authenticate.status |
The status code returned from an authentication attempt. |
$context.customDomain.basePathMatched |
The path for an API mapping that an incoming request matched. Applicable when a client
uses a custom domain name to access an API. For example if a client sends a request to
|
$context.integration.error |
The error message returned from an integration. |
$context.integration.integrationStatus |
For Lambda proxy integration, the status code returned from AWS Lambda, not from the backend Lambda function code. |
$context.integration.latency |
The integration latency in ms. Equivalent to $context.integrationLatency . |
$context.integration.requestId |
The AWS endpoint's request ID. Equivalent to $context.awsEndpointRequestId . |
$context.integration.status |
The status code returned from an integration. For Lambda proxy integrations, this is the status code that your Lambda function code returns. |
$context.integrationLatency |
The integration latency in ms. |
$context.integrationStatus |
For Lambda proxy integration, this parameter represents the status code returned from AWS Lambda, not from the backend Lambda function code. |
$context.responseLatency |
The response latency in ms. |
$context.responseLength |
The response payload length in bytes. |
$context.status |
The method response status. |
$context.waf.error |
The error message returned from AWS WAF. |
$context.waf.latency |
The AWS WAF latency in ms. |
$context.waf.status |
The status code returned from AWS WAF. |
$context.xrayTraceId |
The trace ID for the X-Ray trace. For more information, see Setting up AWS X-Ray with API Gateway REST APIs. |
$input
Variables
The $input
variable represents the method request payload and parameters
to be processed by a mapping template. It provides four functions:
Variable and function | Description |
---|---|
$input.body |
Returns the raw request payload as a string. |
$input.json(x) |
This function evaluates a JSONPath expression and returns the results as a JSON string. For example, For more information about JSONPath, see JSONPath |
$input.params() |
Returns a map of all the request parameters. We recommend that you use |
$input.params(x) |
Returns the value of a method request parameter from the path,
query string, or header value (searched in that order), given a
parameter name string |
$input.path(x) |
Takes a JSONPath expression string ( For example, if the expression
For more information about JSONPath, see JSONPath |
$input
Variable template
examples
Parameter 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:
{ "params" : { "path" : { "path_name" : "path_value", ... } "header" : { "header_name" : "header_value", ... } "querystring" : { "querystring_name" : "querystring_value", ... } } }
You might want to use the $input
variable to get query strings and the
request body with or without using models. You might also want to get the parameter and
the payload, or a subsection of the payload, into your Lambda function. The following
examples show how to do this.
Example JSON mapping template
using $input
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 mapping template
using $input
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 might 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'))" }
Example request and response
using $input
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 Understanding mapping templates.
$stageVariables
Stage variables can be used in parameter mapping and mapping templates and as placeholders in ARNs and URLs used in method integrations. For more information, see Setting up stage variables for a REST API deployment.
Syntax | Description |
---|---|
$stageVariables. |
|
$stageVariables[' |
|
${stageVariables[' |
|
$util
Variables
The $util
variable contains utility functions for use in mapping
templates.
Note
Unless otherwise specified, the default character set is UTF-8.
Function | Description |
---|---|
$util.escapeJavaScript() |
Escapes the characters in a string using JavaScript string rules. NoteThis function will turn any regular single quotes
(
|
$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:
and use the following mapping template
You will get the following output:
|
$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. |