AWS API Gateway offers a tool called Mapping Templates to help you convert the data you have into the data you want. For example, if you want to pass parameters to your API Gateway through a GET request, you'll need a Mapping Template.

If you want to do something like this, you need a Mapping Template.

curl http://api.myapp.com/users/userid001

How Mapping Templates Work

Mapping templates contain three variables: $context, $input, and $util. These three variables offer you everything you need to extract user-submitted data, internal resource data (like an IP address), and a few other things.

$context

Context holds all the contextual information of your API request.

The API ID.

$context.apiId

The AWS Account ID is associated with the request.

$context.identity.accountOwner

The IP address of the API caller (based on x-forwarded-for).

$context.identity.sourceIp

User Agent of the API caller.

$context.userAgent

$input

This is the payload ready to be processed by the templates.

This evaluates the parameters as a JSON path and converts it to a JSON string.

$input.json(x)

This returns a map of the request parameters.

$input.params()

This allows you to manipulate the JSON payload as if it were a native object. For example, you can get an array of string objects and run functions like size().

$input.path(x)

$util

These are utilities for mapping templates such as:

Escape javascript in a string.

$util.escapeJavaScript()

URL encode and decode.

$util.urlEncode()
$util.decode()
$util.escapeJavaScript()

This is helpful if you're planning to store images as base64. Suppose you have no idea what this means, read this other article I wrote a few months ago..

$util.base64Encode()
$util.base64Decode()

Example

Let's create a quick example using the AWS API Gateway.

Step 1 - Create a Resource

Create a resource

Step 2 - Create a Method

create-a-method

Assign a GET method.

Grab all of the information in the request, put it in JSON, and pass that JSON into the lambda function.
create-get-method-w-proxy-integration

Step 3 - Edit Integration Request

Select "Integration Request" to start modifying the Mapping Template.

integration-request

Step 4 - Edit Mapping Template

Once you've clicked on Integration Requests, you can type application/json, select "Empty," and then fill in the parameter you want to map.

Within the Body Mapping Template, we say that the /{id} will map to "orderId" within our lambda function.

edit-mapping-template


Resources