AWS AppSync
AWS AppSync Developer Guide

Resolver Mapping Template Utility Reference

AWS AppSync defines a set of utilities which can be leveraged within a GraphQL resolver to simplify interactions with data sources. Some of these utilities are general to be used with any data source, such as the generation of IDs or timestamps, while others are specific to a data source itself.

Utility Helpers in $util

The $util variable contains general utility methods that make it easier to work with data.

Unless otherwise specified, all utilities use the UTF-8 character set.

$util.qr() and $util.qiet()

Executes a VTL statement while suppressing the returned value of the execution. This is useful if you wish to run methods without using temporary placeholders such as adding items to a map, etc. For example:

#set ($myMap = {}) #set($discard = $myMap.put("id", "first value"))

Becomes:

#set ($myMap = {}) $util.qr($myMap.put("id", "first value"))
$util.escapeJavaScript(String) : String

Returns the input string as a JavasScript escaped string.

$util.urlEncode(String) : String

Returns the input string as an application/x-www-form-urlencoded encoded string.

$util.urlDecode(String) : String

Decodes an application/x-www-form-urlencoded encoded string back to its non-encoded form.

$util.base64Encode( byte[] ) : String

Encodes the input into a base64-encoded string.

$util.base64Decode(String) : byte[]

Decodes the data from a base64-encoded string.

$util.parseJson(String) : Object

Takes "stringified" JSON and returns an object representation of the result.

$util.toJson(Object) : String

Takes an object and returns a "stringified" JSON representation of that object.

$util.autoId() : String

Returns a 128-bit randomly generated UUID.

$util.unauthorized()

Throws Unauthorized for the field being resolved. This can be used in request or response mapping templates to decide if the caller should be allowed to resolve the field.

$util.error(String)

Throws a custom error. This can be used in request or response mapping templates if the template detects an error with the request or with the invocation result.

$util.error(String, String)

Throws a custom error. This can be used in request or response mapping templates if the template detects an error with the request or with the invocation result. Additionally, an errorType can be specified.

$util.error(String, String, Object)

Throws a custom error. This can be used in request or response mapping templates if the template detects an error with the request or with the invocation result. Additionally, an errorType and a data field can be specified. The data value will be added to the corresponding error block inside errors in the GraphQL response. Note: data will be filtered based on the query selection set.

$util.error(String, String, Object, Object)

Throws a custom error. This can be used in request or response mapping templates if the template detects an error with the request or with the invocation result. Additionally, an errorType field, a data field, and a errorInfo field can be specified. The data value will be added to the corresponding error block inside errors in the GraphQL response. Note: data will be filtered based on the query selection set. The errorInfo value will be added to the corresponding error block inside errors in the GraphQL response. Note: errorInfo will NOT be filtered based on the query selection set.

$util.appendError(String)

Appends a custom error. This can be used in request or response mapping templates if the template detects an error with the request or with the invocation result. Unlike $util.error(String), the template evaluation will not be interrupted, so that data can be returned to the caller.

$util.appendError(String, String)

Appends a custom error. This can be used in request or response mapping templates if the template detects an error with the request or with the invocation result. Additionally, an errorType can be specified. Unlike $util.error(String, String), the template evaluation will not be interrupted, so that data can be returned to the caller.

$util.appendError(String, String, Object)

Appends a custom error. This can be used in request or response mapping templates if the template detects an error with the request or with the invocation result. Additionally, an errorType and a data field can be specified. Unlike $util.error(String, String, Object), the template evaluation will not be interrupted, so that data can be returned to the caller. The data value will be added to the corresponding error block inside errors in the GraphQL response. Note: data will be filtered based on the query selection set.

$util.appendError(String, String, Object, Object)

Appends a custom error. This can be used in request or response mapping templates if the template detects an error with the request or with the invocation result. Additionally, an errorType field, a data field, and a errorInfo field can be specified. Unlike $util.error(String, String, Object, Object), the template evaluation will not be interrupted, so that data can be returned to the caller. The data value will be added to the corresponding error block inside errors in the GraphQL response. Note: data will be filtered based on the query selection set. The errorInfo value will be added to the corresponding error block inside errors in the GraphQL response. Note: errorInfo will NOT be filtered based on the query selection set.

$util.validate(boolean, String) : void

If the condition is false, throw a CustomTemplateException with the specified message.

$util.validate(boolean, String, String) : void

If the condition is false, throw a CustomTemplateException with the specified message and error type.

$util.validate(boolean, String, String, Object) : void

If the condition is false, throw a CustomTemplateException with the specified message and error type, as well as data to return in the response.

$util.isNull(Object) : boolean

Returns true if the supplied object is null.

$util.isNullOrEmpty(String) : boolean

Returns true if the supplied data is null or an empty string. Otherwise, returns false.

$util.isNullOrBlank(String) : boolean

Returns true if the supplied data is null or a blank string. Otherwise, returns false.

$util.defaultIfNull(Object, Object) : Object

Returns the first Object if it is not null. Otherwise, returns second object as a "default Object".

$util.defaultIfNullOrEmpty(String, String) : String

Returns the first String if it is not null or empty. Otherwise, returns second String as a "default String".

$util.defaultIfNullOrBlank(String, String) : String

Returns the first String if it is not null or blank. Otherwise, returns second String as a "default String".

$util.isString(Object) : boolean

Returns true if Object is a String.

$util.isNumber(Object) : boolean

Returns true if Object is a Number.

$util.isBoolean(Object) : boolean

Returns true if Object is a Boolean.

$util.isList(Object) : boolean

Returns true if Object is a List.

$util.isMap(Object) : boolean

Returns true if Object is a Map.

$util.typeOf(Object) : String

Returns a String describing the type of the Object. Supported type identifications are: "Null", "Number", "String", "Map", "List", "Boolean". If a type cannot be identified, the return type is "Object".

$util.matches(String, String) : Boolean

Returns true if the specified pattern in the first argument matches the supplied data in the second argument. The pattern must be a regular expression such as $util.matches("a*b", "aaaaab"). The functionality is based on Pattern, which you can reference for further documentation.

Time Helpers in $util.time

The $util.time variable contains datetime methods to help generate timestamps, convert between datetime formats, and parse datetime strings. The syntax for datetime formats is based on DateTimeFormatter which you can reference for further documentation. Below we provide some examples, as well as a list of available methods and descriptions.

Standalone Function Examples

$util.time.nowISO8601() : 2018-02-06T19:01:35.749Z $util.time.nowEpochSeconds() : 1517943695 $util.time.nowEpochMilliSeconds() : 1517943695750 $util.time.nowFormatted("yyyy-MM-dd HH:mm:ssZ") : 2018-02-06 19:01:35+0000 $util.time.nowFormatted("yyyy-MM-dd HH:mm:ssZ", "+08:00") : 2018-02-07 03:01:35+0800 $util.time.nowFormatted("yyyy-MM-dd HH:mm:ssZ", "Australia/Perth") : 2018-02-07 03:01:35+0800

Conversion Examples

#set( $nowEpochMillis = 1517943695758 ) $util.time.epochMilliSecondsToSeconds($nowEpochMillis) : 1517943695 $util.time.epochMilliSecondsToISO8601($nowEpochMillis) : 2018-02-06T19:01:35.758Z $util.time.epochMilliSecondsToFormatted($nowEpochMillis, "yyyy-MM-dd HH:mm:ssZ") : 2018-02-06 19:01:35+0000 $util.time.epochMilliSecondsToFormatted($nowEpochMillis, "yyyy-MM-dd HH:mm:ssZ", "+08:00") : 2018-02-07 03:01:35+0800

Parsing Examples

$util.time.parseISO8601ToEpochMilliSeconds("2018-02-01T17:21:05.180+08:00") : 1517476865180 $util.time.parseFormattedToEpochMilliSeconds("2018-02-02 01:19:22+0800", "yyyy-MM-dd HH:mm:ssZ") : 1517505562000 $util.time.parseFormattedToEpochMilliSeconds("2018-02-02 01:19:22", "yyyy-MM-dd HH:mm:ss", "+08:00") : 1517505562000

Usage with AWS scalars

The following formats are compatible with AWSDate, AWSDateTime, and AWSTime.

$util.time.nowFormatted("yyyy-MM-dd[XXX]", "-07:00:30") : 2018-07-11-07:00 $util.time.nowFormatted("yyyy-MM-dd'T'HH:mm:ss[XXXXX]", "-07:00:30") : 2018-07-11T15:14:15-07:00:30
$util.time.nowISO8601() : String

Returns a String representation of UTC in ISO8601 format.

$util.time.nowEpochSeconds() : long

Returns the number of seconds from the epoch of 1970-01-01T00:00:00Z to now.

$util.time.nowEpochMilliSeconds() : long

Returns the number of milliseconds from the epoch of 1970-01-01T00:00:00Z to now.

$util.time.nowFormatted(String) : String

Returns a string of the current timestamp in UTC using the specified format from a String input type.

$util.time.nowFormatted(String, String) : String

Returns a string of the current timestamp for a timezone using the specified format and timezone from String input types.

$util.time.parseFormattedToEpochMilliSeconds(String, String) : Long

Parses a timestamp passed as a String, along with a format, and return the timestamp as milliseconds since epoch.

$util.time.parseFormattedToEpochMilliSeconds(String, String, String) : Long

Parses a timestamp passed as a String, along with a format and time zone, and return the timestamp as milliseconds since epoch.

$util.time.parseISO8601ToEpochMilliSeconds(String) : Long

Parses an ISO8601 timestamp, passed as a String, and return the timestamp as milliseconds since epoch.

$util.time.epochMilliSecondsToSeconds(long) : long

Converts an epoch milliseconds timestamp to an epoch seconds timestamp.

$util.time.epochMilliSecondsToISO8601(long) : String

Converts a epoch milliseconds timestamp to an ISO8601 timestamp.

$util.time.epochMilliSecondsToFormatted(long, String) : String

Converts a epoch milliseconds timestamp, passed as long, to a timestamp formatted according to the supplied format in UTC.

$util.time.epochMilliSecondsToFormatted(long, String, String) : String

Converts a epoch milliseconds timestamp, passed as a long, to a timestamp formatted according to the supplied format in the supplied timezone.

List Helpers in $util.list

$util.list contains methods to help with common List operations, such as removing or retaining items from a list for filtering use cases.

$util.list.copyAndRetainAll(List, List) : List

Makes a shallow copy of the supplied list in the first argument, retaining only the items specified in the second argument, if they are present. All other items will be removed from the copy.

$util.list.copyAndRemoveAll(List, List) : List

Makes a shallow copy of the supplied list in the first argument, removing any items where the item is specified in the second argument, if they are present. All other items will be retained in the copy.

Map Helpers in $util.map

$util.map contains methods to help with common Map operations, such as removing or retaining items from a Map for filtering use cases.

$util.map.copyAndRetainAllKeys(Map, List) : Map

Makes a shallow copy of the first map, retaining only the keys specified in the list, if they are present. All other keys will be removed from the copy.

$util.map.copyAndRemoveAllKeys(Map, List) : Map

Makes a shallow copy of the first map, removing any entries where the key is specified in the list, if they are present. All other keys will be retained in the copy.

DynamoDB helpers in $util.dynamodb

$util.dynamodb contains helper methods that make it easier to write and read data to Amazon DynamoDB, such as automatic type mapping and formatting. These methods are designed to make mapping primitive types and Lists to the proper DynamoDB input format automatically, which is a Map of the format { "TYPE" : VALUE }.

For example, previously, a request mapping template to create a new item in DynamoDB might have looked like this:

{ "version" : "2017-02-28", "operation" : "PutItem", "key": { "id" : { "S" : "${util.autoId()}" } }, "attributeValues" : { "title" : { "S" : "${ctx.args.title}" }, "author" : { "S" : "${ctx.args.author}" }, "version" : { "N", $ctx.args.version } } }

If we wanted to add fields to the object we would have to update the GraphQL query in the schema, as well as the request mapping template. However, we can now restructure our request mapping template so it automatically picks up new fields added in our schema and adds them to DynamoDB with the correct types:

{ "version" : "2017-02-28", "operation" : "PutItem", "key": { "id" : $util.dynamodb.toDynamoDBJson($util.autoId()) }, "attributeValues" : $util.dynamodb.toMapValuesJson($ctx.args) }

In the previous example, we are using the $util.dynamodb.toDynamoDBJson(...) helper to automatically take the generated id and convert it to the DynamoDB representation of a string attribute. We then take all the arguments and convert them to their DynamoDB representations and output them to the attributeValues field in the template.

Each helper has two version: a version that returns an object (for example, $util.dynamodb.toString(...)), and a version that returns the object as a JSON string (for example, $util.dynamodb.toStringJson(...)). In the previous example, we used the version that returns the data as a JSON string. If you want to manipulate the object before it's used in the template, you can choose to return an object instead, as shown following:

{ "version" : "2017-02-28", "operation" : "PutItem", "key": { "id" : $util.dynamodb.toDynamoDBJson($util.autoId()) }, #set( $myFoo = $util.dynamodb.toMapValues($ctx.args) ) #set( $myFoo.version = $util.dynamodb.toNumber(1) ) #set( $myFoo.timestamp = $util.dynamodb.toString($util.time.nowISO8601())) "attributeValues" : $util.toJson($myFoo) }

In the previous example, we are returning the converted arguments as a map instead of a JSON string, and are then adding the version and timestamp fields before finally outputting them to the attributeValues field in the template using $util.toJson(...).

The JSON version of each of the helpers is equivalent to wrapping the non-JSON version in $util.toJson(...). For example, the following statements are exactly the same:

$util.toStringJson("Hello, World!") $util.toJson($util.toString("Hello, World!"))
$util.dynamodb.toDynamoDB(Object) : Map

General object conversion tool for DynamoDB that converts input objects to the appropriate DynamoDB representation. It's opinionated about how it represents some types: e.g., it will use lists ("L") rather than sets ("SS", "NS", "BS"). This returns an object that describes the DynamoDB attribute value.

String example:

Input: $util.dynamodb.toDynamoDB("foo") Output: { "S" : "foo" }

Number example:

Input: $util.dynamodb.toDynamoDB(12345) Output: { "N" : 12345 }

Boolean example:

Input: $util.dynamodb.toDynamoDB(true) Output: { "BOOL" : true }

List example:

Input: $util.dynamodb.toDynamoDB([ "foo", 123, { "bar" : "baz" } ]) Output: { "L" : [ { "S" : "foo" }, { "N" : 123 }, { "M" : { "bar" : { "S" : "baz" } } } ] }

Map example:

Input: $util.dynamodb.toDynamoDB({ "foo": "bar", "baz" : 1234, "beep": [ "boop"] }) Output: { "M" : { "foo" : { "S" : "bar" }, "baz" : { "N" : 1234 }, "beep" : { "L" : [ { "S" : "boop" } ] } } }
$util.dynamodb.toDynamoDBJson(Object) : String

The same as $util.dynamodb.toDynamoDB(Object) : Map, but returns the DynamoDB attribute value as a JSON encoded string.

$util.dynamodb.toString(String) : String

Convert an input string to the DynamoDB string format. This returns an object that describes the DynamoDB attribute value.

Input: $util.dynamodb.toString("foo") Output: { "S" : "foo" }
$util.dynamodb.toStringJson(String) : Map

The same as $util.dynamodb.toString(String) : String, but returns the DynamoDB attribute value as a JSON encoded string.

$util.dynamodb.toStringSet(List<String>) : Map

Converts a lists with Strings to the DynamoDB string set format. This returns an object that describes the DynamoDB attribute value.

Input: $util.dynamodb.toStringSet([ "foo", "bar", "baz" ]) Output: { "SS" : [ "foo", "bar", "baz" ] }
$util.dynamodb.toStringSetJson(List<String>) : String

The same as $util.dynamodb.toStringSet(List<String>) : Map, but returns the DynamoDB attribute value as a JSON encoded string.

$util.dynamodb.toNumber(Number) : Map

Converts a number to the DynamoDB number format. This returns an object that describes the DynamoDB attribute value.

Input: $util.dynamodb.toNumber(12345) Output: { "N" : 12345 }
$util.dynamodb.toNumberJson(Number) : String

The same as $util.dynamodb.toNumber(Number) : Map, but returns the DynamoDB attribute value as a JSON encoded string.

$util.dynamodb.toNumberSet(List<Number>) : Map

Converts a list of numbers to the DynamoDB number set format. This returns an object that describes the DynamoDB attribute value.

Input: $util.dynamodb.toNumberSet([ 1, 23, 4.56 ]) Output: { "NS" : [ 1, 23, 4.56 ] }
$util.dynamodb.toNumberSetJson(List<Number>) : String

The same as $util.dynamodb.toNumberSet(List<Number>) : Map, but returns the DynamoDB attribute value as a JSON encoded string.

$util.dynamodb.toBinary(String) : Map

Converts binary data encoded as a base64 string to DynamoDB binary format. This returns an object that describes the DynamoDB attribute value.

Input: $util.dynamodb.toBinary("foo") Output: { "B" : "foo" }
$util.dynamodb.toBinaryJson(String) : String

The same as $util.dynamodb.toBinary(String) : Map, but returns the DynamoDB attribute value as a JSON encoded string.

$util.dynamodb.toBinarySet(List<String>) : Map

Converts a list of binary data encoded as base64 strings to DynamoDB binary set format. This returns an object that describes the DynamoDB attribute value.

Input: $util.dynamodb.toBinarySet([ "foo", "bar", "baz" ]) Output: { "BS" : [ "foo", "bar", "baz" ] }
$util.dynamodb.toBinarySetJson(List<String>) : String

The same as $util.dynamodb.toBinarySet(List<String>) : Map, but returns the DynamoDB attribute value as a JSON encoded string.

$util.dynamodb.toBoolean(boolean) : Map

Converts a boolean to the appropriate DynamoDB boolean format. This returns an object that describes the DynamoDB attribute value.

Input: $util.dynamodb.toBoolean(true) Output: { "BOOL" : true }
$util.dynamodb.toBooleanJson(boolean) : String

The same as $util.dynamodb.toBoolean(boolean) : Map, but returns the DynamoDB attribute value as a JSON encoded string.

$util.dynamodb.toNull() : Map

Returns a null in DynamoDB null format. This returns an object that describes the DynamoDB attribute value.

Input: $util.dynamodb.toNull() Output: { "NULL" : null }
$util.dynamodb.toNullJson() : String

The same as $util.dynamodb.toNull() : Map, but returns the DynamoDB attribute value as a JSON encoded string.

$util.dynamodb.toList(List) : Map

Converts a list of object to DynamoDB list format. Each item in the list is also converted to its appropriate DynamoDB format. It's opinionated about how it represents some of the nested objects: e.g., it will use lists ("L") rather than sets ("SS", "NS", "BS"). This returns an object that describes the DynamoDB attribute value.

Input: $util.dynamodb.toList([ "foo", 123, { "bar" : "baz" } ]) Output: { "L" : [ { "S" : "foo" }, { "N" : 123 }, { "M" : { "bar" : { "S" : "baz" } } } ] }
$util.dynamodb.toListJson(List) : String

The same as $util.dynamodb.toList(List) : Map, but returns the DynamoDB attribute value as a JSON encoded string.

$util.dynamodb.toMap(Map) : Map

Converts a map to DynamoDB map format. Each value in the map is also converted to its appropriate DynamoDB format. It's opinionated about how it represents some of the nested objects: e.g., it will use lists ("L") rather than sets ("SS", "NS", "BS"). This returns an object that describes the DynamoDB attribute value.

Input: $util.dynamodb.toMap({ "foo": "bar", "baz" : 1234, "beep": [ "boop"] }) Output: { "M" : { "foo" : { "S" : "bar" }, "baz" : { "N" : 1234 }, "beep" : { "L" : [ { "S" : "boop" } ] } } }
$util.dynamodb.toMapJson(Map) : String

The same as $util.dynamodb.toMap(Map) : Map, but returns the DynamoDB attribute value as a JSON encoded string.

$util.dynamodb.toMapValues(Map) : Map

Creates a copy of the map where each value has been converted to its appropriate DynamoDB format. It's opinionated about how it represents some of the nested objects: e.g., it will use lists ("L") rather than sets ("SS", "NS", "BS").

Input: $util.dynamodb.toMapValues({ "foo": "bar", "baz" : 1234, "beep": [ "boop"] }) Output: { "foo" : { "S" : "bar" }, "baz" : { "N" : 1234 }, "beep" : { "L" : [ { "S" : "boop" } ] } }

Note: this is slightly different to $util.dynamodb.toMap(Map) : Map as it returns only the contents of the DynamoDB attribute value, but not the whole attribute value itself. For example, the following statements are exactly the same:

$util.dynamodb.toMapValues($map) $util.dynamodb.toMap($map).get("M")
$util.dynamodb.toMapValuesJson(Map) : String

The same as $util.dynamodb.toMapValues(Map) : Map, but returns the DynamoDB attribute value as a JSON encoded string.

$util.dynamodb.toS3Object(String key, String bucket, String region) : Map

Converts the key, bucket and region into the DynamoDB S3 Object representation. This returns an object that describes the DynamoDB attribute value.

Input: $util.dynamodb.toS3Object("foo", "bar", region = "baz") Output: { "S" : "{ \"s3\" : { \"key\" : \"foo", \"bucket\" : \"bar", \"region\" : \"baz" } }" }
$util.dynamodb.toS3ObjectJson(String key, String bucket, String region) : String

The same as $util.dynamodb.toS3Object(String key, String bucket, String region) : Map, but returns the DynamoDB attribute value as a JSON encoded string.

$util.dynamodb.toS3Object(String key, String bucket, String region, String version) : Map

Converts the key, bucket, region and optional version into the DynamoDB S3 Object representation. This returns an object that describes the DynamoDB attribute value.

Input: $util.dynamodb.toS3Object("foo", "bar", "baz", "beep") Output: { "S" : "{ \"s3\" : { \"key\" : \"foo\", \"bucket\" : \"bar\", \"region\" : \"baz\", \"version\" = \"beep\" } }" }
$util.dynamodb.toS3ObjectJson(String key, String bucket, String region, String version) : String

The same as $util.dynamodb.toS3Object(String key, String bucket, String region, String version) : Map, but returns the DynamoDB attribute value as a JSON encoded string.

$util.dynamodb.fromS3ObjectJson(String) : Map

Accepts the string value of a DynamoDB S3 Object and returns a map that contains the key, bucket, region and optional version.

Input: $util.dynamodb.fromS3ObjectJson({ "S" : "{ \"s3\" : { \"key\" : \"foo\", \"bucket\" : \"bar\", \"region\" : \"baz\", \"version\" = \"beep\" } }" }) Output: { "key" : "foo", "bucket" : "bar", "region" : "baz", "version" : "beep" }

HTTP helpers in $utils.http

$utils.http contains helper methods that make it easier to deal with http request parameters.

$utils.http.copyHeaders(Map) : Map

Copies the header from the map without the restricted set of HTTP header. This is useful for forwarding Request headers to your downstream HTTP endpoint.

{ ... "params": { ... "headers": $utils.http.copyHeaders($ctx.request.headers), ... }, ... }

XML helpers in $utils.xml

$utils.xml contains helper methods that make it easier to translate XML responses to JSON or a Dictionary.

$utils.xml.toMap(String) : Map

Converts an XML String to a Dictionary.

Input: <?xml version="1.0" encoding="UTF-8"?> <posts> <post> <id>1</id> <title>Getting Started with GraphQL</title> </post> </posts> Output (JSON representation): { "posts":{ "post":{ "id":1, "title":"Getting Started with GraphQL" } } } Input: <?xml version="1.0" encoding="UTF-8"?> <posts> <post> <id>1</id> <title>Getting Started with GraphQL</title> </post> <post> <id>2</id> <title>Getting Started with AWS AppSync</title> </post> </posts> Output (JSON representation): { "posts":{ "post":[ { "id":1, "title":"Getting Started with GraphQL" }, { "id":2, "title":"Getting Started with AWS AppSync" } ] } }

$utils.xml.toJsonString(String) : String

Converts an XML string to a JSON string. This is similar to toMap except that the output is a string. This is useful if you want to directly convert and return the XML response from an HTTP object to JSON.

$utils.xml.toJsonString(String, boolean) : String

Converts an XML string to a JSON string with an optional boolean parameter to determine if you want to string encode the JSON.

Transformation helpers in $utils.transform

$utils.transform contains helper methods that make it easier to perform complex operations against data sources, such as Amazon DynamoDB filter operations.

$util.transform.toDynamoDBFilterExpression(Map) : Map

Converts an input string to a filter expression for use with Amazon DynamoDB.

Input: $util.transform.toDynamoDBFilterExpression({ title:{ contains:"Hello World" } }) Output: { "expression" : "contains(#title, :title_contains)" "expressionNames" : { "#title" : "title", }, "expressionValues" : { ":title_contains" : { "S" : "${context.arguments.filter.title.contains}" } }, }