API Gateway & ‘Single’ Quotes

Very quick post to explain something that has bothered me for longer than it should have today and it needn’t bother anyone else.

When you use API Gateway and Lamba you will likely use the standard ‘Body Mapping’ function that passes through everything in the request to the Lambda function. It parses url parameters and delivers it to Lambda as a nice JSON object you can quickly make use of.

There is one snag however, it doesn’t like single quotes. The minute you pass in a url parameter with a single quote you will get this error:

{"message": "Could not parse request body into json: Unrecognized character escape \'\'\' (code 39)\n at [Source: [B@7d54c1f5; line: 7, column: 27]"}

Ugh you think, it was all working so nicely. Well there’s a simple fix. Replace your body mapping template with this one, actually there are only two line changes to the default one.

## See http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html
## This template will pass through all parameters including path, querystring, header, stage variables, and context through to the integration endpoint via the body/payload
#set($allParams = $input.params())
"body-json" : $input.json('$'),
"params" : {
#foreach($type in $allParams.keySet())
#set($params = $allParams.get($type))
"$type" : {
#foreach($paramName in $params.keySet())
#set($pval = $util.escapeJavaScript($params.get($paramName)).replaceAll("\\'","'"))
"$paramName" : "$pval"
"stage-variables" : {
#foreach($key in $stageVariables.keySet())
"$key" : "$util.escapeJavaScript($stageVariables.get($key))"
"context" : {
"account-id" : "$context.identity.accountId",
"api-id" : "$context.apiId",
"api-key" : "$context.identity.apiKey",
"authorizer-principal-id" : "$context.authorizer.principalId",
"caller" : "$context.identity.caller",
"cognito-authentication-provider" : "$context.identity.cognitoAuthenticationProvider",
"cognito-authentication-type" : "$context.identity.cognitoAuthenticationType",
"cognito-identity-id" : "$context.identity.cognitoIdentityId",
"cognito-identity-pool-id" : "$context.identity.cognitoIdentityPoolId",
"http-method" : "$context.httpMethod",
"stage" : "$context.stage",
"source-ip" : "$context.identity.sourceIp",
"user" : "$context.identity.user",
"user-agent" : "$context.identity.userAgent",
"user-arn" : "$context.identity.userArn",
"request-id" : "$context.requestId",
"resource-id" : "$context.resourceId",
"resource-path" : "$context.resourcePath",
"radiobase" : "now-playing-submit"

Read More