Checking for null in an API Gateway transform

Amazon’s API Gateway provides the ability to transform a response from an endpoint into a different format for return to the client.

One thing I wished to accomplish with this was to return a value to the client, only if it was set in the response. Essentially, I wanted to check for the existence of a JSON property in the response, and react accordingly. The solution was not obvious to me, and this post serves to record that solution for posterity.

For example, consider a response from an integration endpoint that may or may not have a next_url field.

    "next_url": ""

Our response to the client will check for the existence of this field, and return it if it exists. Otherwise, it will return nothing. To check for null values, we use an #if block that checks if the value of a field is equal to the empty string #if("$!nextUrl" != "").

#set($inputRoot = $input.path('$'))
#set($nextUrl = $inputRoot.next_url)
    #if("$!nextUrl" != "")
    "next_url": "$nextUrl",

Like this post? Subscribe via RSS or email to never miss an update.