'How to add functions like generating random UUID in velocity template for request/response mapping in API gateway

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.



Solution 1:[1]

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.

Solution 2:[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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Michael - sqlbot
Solution 2