6

I am creating a request mapping template for AWS API gateway. In that template I want to customize the request params based on certain conditions and apply operators.

 #foreach($header in $input.params().header.keySet())
     #if($header=="id")#set($idVal = 
     $util.escapeJavaScript($input.params().header.get($header)))
         #if($idVal.matches("^[0-9a-f]{4}-[0-9A-Z]{3}$"))
             "$header":"$idVal"
         #else
           #set($random = UUID.randomUUID())
          "$header":"$random"
         #end
     #else

For example, in the above template based on if condition I want to generate randomUUID and add to the header. But when I test, the id value is set to empty string.

How can I use packages and java functions support in velocity template mapping api gateway? Also, please share any reference to wellformed template, it would be really useful to learn more.

John Rotenstein
  • 241,921
  • 22
  • 380
  • 470
Ali
  • 253
  • 4
  • 13

2 Answers2

9

VTL as used in API Gateway is not extensible with your own packages. Only the built-in variables and $util functions can be used.

You may find that $context.requestId contains a suitable UUID for your purpose, unique to each request. Note that if you are using a Lambda integration, this value differs from Lambda's context.requestId which only coincidentally has the same name.

Or, the rightmost 33 characters of $context.xrayTraceId should contain a 4 byte timestamp (8 hex digits) + '-' + a 96-bit unique value (24 hex digits) from which you could construct a serviceable UUID with some light string manipulation.

Michael - sqlbot
  • 169,571
  • 25
  • 353
  • 427
  • 1
    `$context.requestId` is what is mentioned in the AWS blog for the hash key: https://aws.amazon.com/blogs/compute/using-amazon-api-gateway-as-a-proxy-for-dynamodb/ – Sebastian J. May 08 '20 at 04:00
2

For AppSync users:

You can't use packages but you can use the $util helpers

For example you can use $util.autoId() to generate your UUID.

Diego Ponciano
  • 453
  • 5
  • 12