Mike MacDonagh's Blog

Somewhere in the overlap between software development, process improvement and psychology

Tag Archives: javascript

How to call a webservice api from Amazon Alexa using Javascript in a Lambda function

This wasn’t trivial and I’ve seen a lot of questions about it online so I thought I’d share how I did this to get Alexa to respond to questions about my kids pocket money 🙂

You can call a URL like this:
(note I’m assuming a JSON response, you’d need to modify for non-JSON)

var http = require('http');

function getWebRequest(url,doWebRequestCallBack) {
    http.get(url, function (res) {
        var webResponseString = '';
        //console.log('Status Code: ' + res.statusCode);

        if (res.statusCode != 200) {
            doWebRequestCallBack(new Error("Non 200 Response"));
        }

        res.on('data', function (data) {
            webResponseString += data;
        });

        res.on('end', function () {
            //console.log('Got some data: '+ webResponseString);            
            var webResponseObject = JSON.parse(webResponseString);            
            if (webResponseObject.error) {
                //console.log("Web error: " + webResponseObject.error.message);
                doWebRequestCallBack(new Error(webResponseObject.error.message));
            } else {
                //console.log("web success");
                doWebRequestCallBack(null, webResponseObject);
            }
        });
    }).on('error', function (e) {
        //console.log("Communications error: " + e.message);
        doWebRequestCallBack(new Error(e.message));
    });
}

You can then use it like this from inside an intent handler:

function getPocketMoney(intent, session, callback) {

    let shouldEndSession = false;
    let repromptText = null;
    let speechOutput = '';
    let cardTitle = '';

    let url = "http://mypocketmoneyservice/getpocketmoney?person=mike";

    getWebRequest(url, function webResonseCallback(err, data) {
        if (err) {
            speechOutput = "Sorry I couldn't connect to the server: " + err;
        } else {
            //something like this
            const balance = data.pocketmoney.person.balance;
            speechOutput = `${person} has £${balance} pocket money.`;            
            callback({}, buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));                   
        }
    });
}
Advertisements
%d bloggers like this: