Using Serverless for an API Endpoint (XML > JSON converter)

Hi Guys,

Really impressed with the Serverless framework and how easy it makes deployments to AWS. Great job!!

I am working on a small app which basically acts as a ‘middle-man’ for a XML API.

My objective is to point Zapier at my Lambda Function and it will collect the data from a 3rd party XML API call, convert the results into JSON and print to screen.

Zapier will then process the JSON.

The problem I am experiencing is that its not that easy to push my JSON data (converted with the XML2JS module) back via the callback.

I have it mostly working but the output looks like something like this:

{"message":"[{\"id\":[\"123456\"],\"affiliate_name\":[\"Some Name\"]]"}

ideally I just want the raw json so no message just

{"id":["123456"],"affiliate_name":["Some Name"]]}

This is all working fine until I have to JSON encode the responce for the callback.

module.exports.newAffiliates = (event, context, callback) => {

 getNewAffiliates(config, function(last10Affs) {

                console.log('CLEAN JSON: ' + last10Affs);

                const response = {
                    statusCode: 200,
                    headers: {
                        "Access-Control-Allow-Origin" : "*" // Required for CORS support to work
                    },
                    body: JSON.stringify({
                        message: last10Affs,
                        //input: event,
                    }),
                };

                console.log(response);

                callback(null, response);

            });

I tried passing the callback responce in different ways, but it always falls over.

Any help would be much apprciated.

Andrew Curioso @andrewcurioso

Answered this for me, thank you :slight_smile:

That is normal if you are seeing the output directly from Lambda. The body part of the message is double-encoded (an encoded Json string inside a Json object) which is why you are seein the slashes. But API gateway should unescape the slashes on the way through and what will end up on the client-side is the version without the slashes.

For completeness I also removed the { message: }

 const response = {
                statusCode: 200,
                headers: {
                    "Access-Control-Allow-Origin" : "*" // Required for CORS support to work
                },
                body: JSON.stringify(last10Affs
                    //input: event,
                ),
            };

            console.log(response);

            callback(null, response);

        });

Hope it helps someone else in the future.