1

I'm working on AWS lambda + API Gateway, and I need to pass an array of numbers in the url (GET method) for a REST call. It seems a good way is to pass the numbers as string (comma separated) and then use JSON.parse for the conversion to an array of numbers.

Following is the AWS lambda code I'm using;

exports.handler = (event, context, callback) => { var arr = JSON.parse('[' + event.numbers + ']'); console.log("array: " + arr); // TODO implement callback(null, 'Hello from Lambda'); }; 

I'm testing this function in AWS Lambda using this Input test event;

{ "numbers": "1,5" } 

And everything works as expected; no errors.

However, when I test it via API Gateway, and passing the numbers as string in the query, I get following error (observed via CloudWatch);

*19:19:02 START RequestId: eabab882-8cee-11e7-8e2f-79d3086e061f Version: $LATEST 19:19:02 2017-08-29T19:19:02.688Z eabab882-8cee-11e7-8e2f-79d3086e061f SyntaxError: Unexpected token u in JSON at position 1 at Object.parse (native) at exports.handler (/var/task/index.js:4:20) 19:19:02 END RequestId: eabab882-8cee-11e7-8e2f-79d3086e061f 19:19:02 REPORT RequestId: eabab882-8cee-11e7-8e2f-79d3086e061f Duration: 215.25 ms Billed Duration: 300 ms Memory Size: 128 MB Max Memory Used: 18 MB 19:19:02 RequestId: eabab882-8cee-11e7-8e2f-79d3086e061f Process exited before completing request* 

This is the request passed to lambda as shown in the log;

"body-json" : {}, "params" : { "path" : { } ,"querystring" : { "numbers" : "1,6" } ,"header" : { } }, "stage-variables" : { }, 

I can't figure out what the problem is, since I'm passing same string in both cases.

I would appreciate any help.

Thanks Gus

1 Answer 1

2

With this input json informed, you need to get it like this:

var arr = JSON.parse('[' + event.params.querystring.numbers + ']'); 

rather than:

var arr = JSON.parse('[' + event.numbers + ']'); 

Or make a body mapping template to stay the way you want:

{ "number": "$input.params('number')" } 

http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html

I hope I have helped!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.