I am making an Alexa skill and need it to query an API, however it just simply doesnt seem to work and i have tried 1 million different ways. Would be great if someone could take a look at the code below and add a basic API query, thanks!
const playersOnlineHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return (request.type === 'IntentRequest'
&& request.intent.name === 'playersOnlineIntent');
},
handle(handlerInput) {
const data =https.get("URL");
const x = "Hello";
const speechOutput = "There is currently" + data + "players online";
return handlerInput.responseBuilder
.speak(speechOutput)
.getResponse();
},
};
You can try this code for HTTP GET API calls
const playersOnlineHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return (request.type === 'IntentRequest'
&& request.intent.name === 'playersOnlineIntent');
},
handle(handlerInput) {
let data;
const request = require("request");
let options = { method: 'GET',
url: 'http://exaple.com/api.php',
qs:
{ action: 'query' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
let json = body;
let obj = JSON.parse(json);
data = obj.element.value;
});
const x = "Hello";
const speechOutput = "There is currently" + data + "players online";
return handlerInput.responseBuilder
.speak(speechOutput)
.getResponse();
},
};
You can refer to the following snippet. Works well with https
built-in module
handle(handlerInput) {
https.get('https://jsonplaceholder.typicode.com/todos/1', res => {
res.setEncoding("utf8");
let body = "";
res.on("data", data => {
body += data;
});
//On receiving the entire info from the API
res.on("end", () => {
body = JSON.parse(body);
speechOutput += 'Sample Info' + body.userId;
return handlerInput.responseBuilder
.speak(speechOutput)
.getResponse();
});
});
},
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.