Retrieving Data From A 3rd Party API Within Functions

358 views
Skip to first unread message

Kevin H

unread,
Jul 16, 2018, 12:34:57 PM7/16/18
to Twilio Functions
Howdy, everyone!

I'm new to Twilio, and I code in Java.  I'm trying to build an application within Functions that accepts an SMS message from the user, then accesses a third-party API, finds information in that JSON file, then sends an SMS to the user with their desired information.  Right now, I am stuck on how to get and store the third-party API in an object and access its specific JSON elements to send back to the user.  How is it done?  I appreciate any help anyone can provide!

shane elliott

unread,
Jul 16, 2018, 6:30:57 PM7/16/18
to Twilio Functions
I think I understand you want to call an external API (URL) and get the json data back.  

if so, here is a working example:

var got = require('got');

exports.handler = function(context, event, callback) {
  let twiml = new Twilio.twiml.MessagingResponse();
   const url ='https://randomuser.me/api';
  
got(url, {json: true})
  .then(function(response) {
   console.log(response.body)
   twiml.message(JSON.stringify(response.body))
   callback(null, twiml);
  })
  .catch(function(error) {
    callback(error)
  })

};

Kevin H

unread,
Jul 16, 2018, 6:39:36 PM7/16/18
to Twilio Functions
Thank you for the help!  I really appreciate it when people like yourself take the time to help others!

Unfortunately, I've already tried that and I get this error message: "{"message":"Cannot find module 'got'","name":"Error","stack":"Error: Cannot find module 'got'\n at Function.Module._resolveFilename (module.js:547:15)\n at Function.Module._load (module.js:474:25)\n at Module.require (module.js:596:17)\n at Module.twilioRequire [as require] (/var/task/node_modules/enigma-lambda/src/dependency.js:28:21)\n at require (internal/module.js:11:18)\n at Object.<anonymous> (/var/task/handlers/ZF2f83a41e50b67c816f0d43ef99c3d8d1.js:1:73)\n at Modul..."

Any knowledge on how to fix this?  The 'got' is obviously in the code.

Alan

unread,
Jul 16, 2018, 6:55:14 PM7/16/18
to Twilio Functions
Under the Twilio Function, go to Configure and add got (latest version is: 8.3.2 - https://www.npmjs.com/package/got).

From logged in Twilio Console Session:

Click "+" under Dependencies
Name: got
Version: 8.3.2

Click out of the edit box and then click save (verify that got is now listed)

Kevin H

unread,
Jul 16, 2018, 6:58:15 PM7/16/18
to Twilio Functions
That worked!  Wow it was right under me the whole time!  Thank you so much!

shane elliott

unread,
Jul 16, 2018, 7:13:29 PM7/16/18
to Twilio Functions
sorry,  forgot to tell you to add the got module....:)
Reply all
Reply to author
Forward
0 new messages