imnikhilanand
imnikhilanand

Reputation: 31

How to call an API from Dialog Flow using get method?

My question is about the the use of API in Webhook. I used this code for calling an external API from my localhost using ngrok. I have tried Using 3rd party API within Dialogflow Fulfillment as well, but still not working for my case. This is my code -

'use strict';

var https = require ('https');

const functions = require('firebase-functions');

const {WebhookClient} = require('dialogflow-fulfillment');

const {Card, Suggestion} = require('dialogflow-fulfillment');

process.env.DEBUG = 'dialogflow:debug';

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' + 
JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));

function welcome(agent) {
  agent.add(`Welcome to my agent!`);
}

function fallback(agent) {
 agent.add(`I didn't understand`);
 agent.add(`I'm sorry, can you try again?`);
}

function get_products(agent){
  var url = 'https://705861b5.ngrok.io/products';
  https.get(url, function(res){
    var body = '';
    res.on('data', function(chunk){
      body += chunk;
    });
    res.on('end', function(){
     var respose_jquery = JSON.parse(body);
     agent.add("Got a response: ", respose_jquery.product_name);
    });
  }).on('error', function(e){
    agent.add("Got an error: ", e);
  });   
}

let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Default Fallback Intent', fallback);
intentMap.set('show_products', get_products);
agent.handleRequest(intentMap);

});

Upvotes: 1

Views: 2052

Answers (1)

Prisoner
Prisoner

Reputation: 50711

The issue is that the dialogflow-fulfillment library assumes that you will return a Promise if you do any async functions, such as the https calls in your get_products() function.

Although you can wrap your code in something that returns a Promise, the easiest way to do this is to use something like the request-promise-native library. It might look something like this (untested):

const rp = require('request-promise-native');

function get_products(agent){
  var url = 'https://705861b5.ngrok.io/products';
  var options = {
    uri: url,
    json: true
  };
  return rp.get( options )
    .then( body => {
      agent.add("Got a response: "+body.product_name);
    })
    .error( err => {
      agent.add("Got an error: " + e);
    });
}

Upvotes: 1

Related Questions