Hello and good evening all!
I have setup an API call in my Alexa app and I'm trying to get a basic understanding of why it isn't working with the URL/response I have.
I know the API call works because when I replace 'host' with 'api.icndb.com' and 'path' with '/jokes/random' it works (when I access the response data using response.value.quote).
My API call will not work with the URL I have provided or maybe perhaps it's the way I'm trying to access the data. The API provides data in an array with objects nested inside of it which is different from the aforementioned URL.
To see what I'm referring to, here is the URL for the sample Alexa skill that I built my app from with the 'api.icndb.com' API I'm referring to.
Here is my code:
/* eslint-disable func-names */
/* eslint-disable no-console */
const Alexa = require('ask-sdk');
var https = require('https')
const LaunchRequestHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'LaunchRequest'
},
handle(handlerInput) {
return handlerInput.responseBuilder
.speak('Welcome to Simpson Speak')
.getResponse();
}
};
const GetQuoteHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest' && request.intent.name === 'GetQuote';
},
async handle(handlerInput) {
const response = await httpGet();
console.log(response);
return handlerInput.responseBuilder
.speak(response[0].author)
.getResponse()
}
};
function httpGet(){
return new Promise(((resolve, reject) => {
var options = {
host: 'thesimpsonsquoteapi.glitch.me',
port: 443,
path: '/quotes',
method: 'GET',
};
const request = https.request(options, (response) => {
response.setEncoding('utf8');
let returnData = '';
response.on('data', (chunk)=>{
returnData += chunk;
});
response.on('end',()=>{
resolve(JSON.parse(returnData));
});
response.on('error', (error)=>{
reject(error);
});
});
request.end();
}));
};
const skillBuilder = Alexa.SkillBuilders.standard();
exports.handler = skillBuilder
.addRequestHandlers(
LaunchRequestHandler,
GetQuoteHandler
)
.lambda();
This code will work with your httpGet function.
const GetQuoteHandler = {
canHandle(handlerInput) {
return handlerInput.requestEnvelope.request.type === 'IntentRequest'
&& handlerInput.requestEnvelope.request.intent.name === 'GetQuote';
},
async handle(handlerInput) {
const {responseBuilder } = handlerInput;
const response = await httpGet();
console.log(response);
const items = response[0]
const item = items.quote
var speechText = "Your quote is" + JSON.stringify(item)
return responseBuilder
.speak(speechText)
.reprompt("don't even know that one")
.getResponse();
}
}