Search code examples
amazon-web-servicesmappingvelocityaws-api-gateway

Velocity template parses invalid JSON as valid JSON


I have the following template that works how I expect it to:

#set($allParams = $input.params())
{
    "body" : $input.json('$'),
    "params" : {
    #foreach($type in $allParams.keySet())
        #set($params = $allParams.get($type))
        "$type" : {
        #foreach($paramName in $params.keySet())
            "$paramName" : "$util.escapeJavaScript($params.get($paramName))"#if($foreach.hasNext),#end
        #end
        }#if($foreach.hasNext),#end
    #end
    }
}

What is troublesome to me is that this template will still parse invalid JSON.

For example given the following invalid JSON before transformation:

{
    "example": !@#$%^&*()_+
}

Using the template above will transform it to:

{
    "body" : {
        "asdasd": "!@#$%^&*()"
    },
    ...
}

My question is why? Shouldn't $input.json('$') fail to parse an invalid JSON string?

Redacted logs below:

Execution log for request test-request
Fri Oct 06 21:27:13 UTC 2017 : Starting execution for request: test-invoke-request
Fri Oct 06 21:27:13 UTC 2017 : HTTP Method: POST, Resource Path: /equipment
Fri Oct 06 21:27:13 UTC 2017 : Method request path: {}
Fri Oct 06 21:27:13 UTC 2017 : Method request query string: {}
Fri Oct 06 21:27:13 UTC 2017 : Method request headers: {}
Fri Oct 06 21:27:13 UTC 2017 : Method request body before transformations: {
    "asdasd": 123123$%^&*()
}
Fri Oct 06 21:27:13 UTC 2017 : Endpoint request body after transformations: {
    "body" : {"asdasd":"123123$%^&*()"},
    "params" : {
....

Solution

  • I was able to solve my issue by using a request body model:

    {
        "$schema": "http://json-schema.org/draft-04/schema#",
        "title": "Example",
        "type": "object",
        "required": [
            "example"
        ],
        "properties": {
            "example": {
                "type":"string"
            }
        }
    }
    

    So API Gateway will check the request body against the JSON schema model above before sending it over to Lambda.