Tobi
Tobi

Reputation: 2828

Return JSONP via AWS Lambda/API Gateway

I'm trying to return jsonp as in callbackname(data.strified)

callback( null, 
    ( !!event.cb && event.cb.length > 0 ) 
    ? event.cb.replace( /[^a-z0-9_]/i, '' ) + '(' + JSON.stringify( data ) + ')'
    : data
);

My quick and dirty way now returns the data and if ?cb=test is given it returns:

"test({\"valid\":false,\"data\":false})"

Is there anyway to get rid of the quotes and escape characters? The API should work with and without callback set.

Upvotes: 3

Views: 2181

Answers (3)

Teebs
Teebs

Reputation: 795

As Çağatay Gürtürk pointed out, you stringify your result and return it.

However, if your lambda also accepts non callbacks, you can check in the VTL template:

API Gateway and in Integration Response part:

#if($input.params('callback') != "")
$util.parseJson($input.json('$'))
#else
$input.json('$')
#end

Upvotes: 1

Cagatay Gurturk
Cagatay Gurturk

Reputation: 7246

Given that you have this type of lambda function:

exports.handler = function(event, context) {
    var data={"test":"data"};
    context.done( null, 
            ( !!event.cb && event.cb.length > 0 ) 
            ? event.cb.replace( /[^a-z0-9_]/i, '' ) + '(' + JSON.stringify( data ) + ')'
            : data
    );
};

When you give it an event like

{
  "cb": "callback"
}

It will give this output:

"callback({\"test\":\"data\"})"

So far, so good. Now you come to API Gateway and in Integration Response part you write this

$util.parseJson($input.json('$'))

Than you will get callback({"test":"data"}) as output when you invoke the API Gateway endpoint.

Upvotes: 5

Balaji
Balaji

Reputation: 1046

You can use an integration mapping template to do this. Something like this should help you to parse the Json.

$util.parseJson($input.json('$'))

Here are more details about mapping templates.

Upvotes: 1

Related Questions