aws-api-gatewayaws-step-functionsvtlx-www-form-urlencoded

VTL Mapping Template To Convert Encoded Form Data Into JSON Object For AWS Step Function


How to convert application/x-www-form-urlencoded data coming via POST request into API gateway into a JSON object so you may send said object to Step Functions without first sending to Lambda for pre-processing.

(Answer included below)


Solution

    1. Inside of your API, go to Integration Request > Edit Integration Request
    2. Scroll down to mapping templates
    3. Set content type to application/x-www-form-urlencoded
    4. Paste the following mapping template below, be sure to update the Step Function ARN appropriately, and be sure your IAM role has valid permissions to StartExecution/StartSyncExecution

    Mapping Template:

    #set($data = "")
    
    #foreach( $token in $input.path('$').split('&') )
    #set( $keyVal = $token.split('=') )
    #set( $keyValSize = $keyVal.size() )
    #if( $keyValSize >= 1 )
        #set( $key = $util.urlDecode($keyVal[0]) )
        #if( $keyValSize >= 2 )
            #set( $val = $util.urlDecode($keyVal[1]) )
        #else
            #set( $val = '' )
        #end
    #end
    
    
    #set($data = 
    "${data}\""${key}\"":\""$util.escapeJavaScript($val)\""#if($foreach.hasNext),#end")
    #end
    
    
    {
      "input": "{$data}",
      "stateMachineArn": "YOUR STEP FUNCTION ARN"
    }
    

    Given your role has proper permissions, this mapping template will result in your step function executing properly with a beautifully formatted JSON object inputted.