API Gateway Mapping Template optional field

2.5k views Asked by At

I've been working with Mapping Templates on AWS API Gateway, in particular for DynamoDB integration. And I found very inconvenient to check against optional fields. For example I have a JSON payload like this:

{
    "optional_field": "abcd" 
}

now to put it to the database I use a mapping like this:

#set($hasOptionalField = $input.path('$.optional_field') != "")
{
    "TableName": "A_Table",
    "Item": {
        "id": {"S": "$context.requestId"}
#if($hasOptionalField),
        "optional_field": {"S": "$input.path('$.optional_field')"}
#end
    }
}

According to Apache Velocity Reference I should be able to use much simpler syntax do check for null, empty, false or zero and fallback automatically to some alternative value, something beautiful like this:

{
    "TableName": "A_Table",
    "Item": {
        "id": {"S": "$context.requestId"},
        "optional_field": {"S": "${input.path('$.optional_field')|'no_data'}"}
    }
}

I could just leave it as is without any fallback, but DynamoDB API gives you an error if try to put empty string as an attribute value.

It seems like API Gateway Mapping Templates does not 100% implement Apache Velocity specification?

1

There are 1 answers

0
krtsh On

You could fall back to a default value for the optional fields from the payload with #if-else.

#set($req = $input.path('$'))
#if($req.optional_field != "")
#set( $my_default_value = $input.path('$.optional_field'))
#else
#set ($my_default_value = "no_data")
#end
{
    "TableName": "A_Table",
    "Item": {
        "id": {
            "S": "$context.requestId"
        },
        "optional_field": {
            "S": "$my_default_value"
        }
    }
}