Making API requests with JavaScript

One of, if not the most important component of interacting with third-party services is communicating with their APIs. Standing for Application Programming Interface, this is the primary way in which different websites, applications and web services can talk to each other, receiving and sending data back and forth. This tutorial will serve as a basic introduction to connecting to a web API via JavaScript, and being able to receive or read GET requests that return data in JSON (or JavaScript Object Notation) format. This tutorial assumes basic knowledge of JavaScript objects and accessing properties, but is otherwise intended for individuals with no prior experience working with APIs.

Introduction

For this tutorial, we will be going through the Ghibli API, which was set up to introduce people to using Application Programming Interfaces (as well as for aficionados of the films of Studio Ghibli).

The API is broken up into 5 different modules or components for different classes of data related to Studio Ghibli (Films, People, Locations, Species and Vehicles). Each one of these components is more formally referred to as an endpoint. When making a call to the endpoint via GET (or another similar method, such as fetch), the endpoint will return an array of data specific to that category, in JSON format. For example, the endpoint for Films would look something like this:

API requests with JavaScript

We’ll take the endpoint for Films (available here), make a call via GET, then log various parts of the data to the console.

// Make a new XMLHttpRequest and save it to a variable
var receive = new XMLHttpRequest();

// Indicate the endpoint we'd like to open, via the `GET` method
receive.open('GET', 'https://ghibliapi.herokuapp.com/films', true);

// Execute the code within the function once the endpoint is loaded
receive.onload = function () {

  // Parse the incoming data into JSON format  
  var incoming = JSON.parse(this.response);
  
  // Use the .map array method to iterate over each index in the Films
  // endpoint, then access the releae date, title and Rotten Tomatoes 
  // score from each, logging them to the console with some additional
  // formatting
  incoming.map(films => {
      console.log(films.release_date + " : " + films.title + " -- (" +  films.rt_score + "% on Rotten Tomatoes)");
    });
};

// Send the actual request, to execute the function assigned to 
// `receive.onload`
receive.send();    

Inputting the code above into your browser console, or by running as a JavaScript file linked to a webpage should return the following:

API requests with JavaScript

…where we are displaying the release year, the name of the film and its overall rating on Rotten Tomatoes (along with some additional formatting for better legibility)

The API Call Explained

The documented notes within the script above should make most of the API call explanatory, but the manipulation of the data within receive.onload is worth further details.

The .map() array is used to iterate over each individual index within the Film endpoint (i.e. each film). A for loop could be used here just as well, although .map() does the same thing with far less code. .map() takes a callback function (written here in ES6 syntax). The code within the callback function is executed for each item in the endpoint, retrieving its release date (films.release_date), title (films.title) and score on Rotten Tomatoes (films.rt_score).

For simplicity’s sake, a console.log message is used for each item, but this data could easily be added to HTML elements on the page, or sorted further with other array methods (i.e. filter out only films from the 1980s). While there is much more to working with API services, this is a high-level overview of the mechanics of retrieving data from an API’s endpoints.

Resources

Post a Comment

Comments are moderated. Your email is kept private. Required fields are marked *

© 2018 Sunlight Media LLC - Web Design Company