Getting started with the Star Wars API in Node.js using Twilio Functions

December 18, 2017
Written by
Sam Agnew
Twilion

star_wars_episode_viii_the_last_jedi_2017_4k-HD

Star Wars: The Last Jedi comes out tonight and I am massively excited to see it. However, some of my other friends who are seeing the movie aren’t as familiar with the Star Wars universe as I am. Let’s use the amazing Star Wars API to build a Twilio powered SMS hack to help fix that.

We are going to use Twilio Functions to avoid having to go through the hassle of deploying a web application, the Star Wars API to gather relevant data on Star Wars characters, the Giphy API to grab GIFs of those characters, and Twilio SMS to facilitate the communications with our users.

Working with the Star Wars API

The Star Wars API is a very simple REST API that only functions using GET requests. Twilio functions gives us access to Got, which we can use for these HTTP requests. In particular, we’ll be working with the people endpoint.

Here’s some example code on how to use Got to grab the data on Luke Skywalker, if you want to run them in your own terminal to test things out, you’ll need to have node.js and npm installed, and will need to run npm install got in the directory your code lives in:

let got = require('got');

got('https://swapi.co/api/people/1/', { json: true })
.then(function(response) {
  console.log(response.body.name); // Luke Skywalker
});

There’s also search functionality that we can use to find characters given a query:

let got = require('got');

got('https://swapi.co/api/people/?search=luke', { json: true })
.then(function(response) {
  console.log(response.body.results[0].name); // Luke Skywalker
});

If you want to get access to a character’s species or homeworld, you have to make another API request:

let got = require('got');

got('https://swapi.co/api/people/?search=luke', { json: true })
.then(function(response) {
  console.log(response.body.results[0].name); // Luke Skywalker
  return got(response.body.results[0].homeworld, { json: true });
}).then(function(response) {
  console.log(response.body.name); // Tatooine
});

Now that we know how to work with the Star Wars API, let’s put it in a Twilio function.

Setting up a Twilio Function

You’ll need to create a Twilio account if you don’t already have one. From the Twilio Functions page in your Twilio Console, create a new Function and select the “Blank” template as seen in this image:

Give your function a name and a path.

Now insert the following code for our app, and click save:

exports.handler = function(context, event, callback) {
  let got = require('got');

  let twiml = new Twilio.twiml.MessagingResponse();
  let query = event.Body;
  let swapiUrl = `https://swapi.co/api/people/?search=${query}`;
  let giphyUrl = 'https://api.giphy.com/v1/gifs/search';
  let giphyApiKey = 'dc6zaTOxFJmzC'; // This is the default/demo public API key.

  got(swapiUrl, { json: true }).then(function(response) {
    if(response.body.count == 0) {
      twiml.message("I couldn't find any Star Wars characters that matched your search. Maybe they aren't canon anymore? :P");
      return callback(null, twiml);
    }

    // Take the Star Wars character that most closely matches the query.
    let bestMatch = response.body.results[0];
    let name = bestMatch.name;
    let species = '';
    let homeworld = '';
    let speciesUrl = bestMatch.species[0];
    let homeworldUrl= bestMatch.homeworld;
    console.log(name);

    got(speciesUrl, { json: true }).then(function(response) {
      species = response.body.name;
      console.log(species);
      return got(homeworldUrl, { json: true });
    }).then(function(response) {
      homeworld = response.body.name;
      console.log(homeworld);
      return got(`${giphyUrl}?api_key=${giphyApiKey}&q=${name}`, { json: true });
    }).then(function(response) {
      console.log(response.body.data[0].images.downsized.url);
      const message = twiml.message();
      message.body(`${name} is a ${species} from planet ${homeworld}`);

      // Take the first GIF in the search. Generate TwiML for the SMS response.
      message.media(response.body.data[0].images.downsized.url);
      callback(null, twiml);
    }, function(reason) {
      console.error( 'onRejected function called: ', reason );
    });
  });
};

What’s happening in this code is that the user:

  • Texts the Twilio phone number that you will link this function to.
  • Your function executes and makes several back-to-back requests to the Star Wars API to grab all of the relevant data: the character’s name, species, and home planet.
  • After the Star Wars data is gathered, a request to the Giphy API is made to grab a GIF of the character your user searched for.
  • When all is said and done, some TwiML is generated to tell Twilio to respond with a text message.

Getting everything running

Now buy a Twilio number and link it up to your function. After buying your number, scroll down to the “Messaging” section and configure it to call your function whenever it receives a text message, as seen in this image:

Now you should be able to text your phone number and see some Star Wars info!

This is only the tip of the iceberg. You can add even more to include what vehicles and starships a character is affiliated with. The data of the Star Wars universe is now at your fingertips. In the meantime, I’m going to head out and watch the new Star Wars movie.

Feel free to reach out if you have any questions or comments or just want to show off the cool stuff you’ve built.