You are here

How to Connect to an API with JavaScript

Over on her blog, Tania Rascia teaches you how to use JavaScript to make API calls in a simple way, without a server, dependencies, or build tools. The project outcome will show a grid with movies produced by Studio Ghibli, a Japanese animation film studio based in Tokyo Japan. 

The source code is on GitHub and your web app, after development, will look like this:

In the tutorial, the author explains how to use the HTTP verb request GET using JavaScript (using actioning verbs to CRUD: create, read, update, and delete), and how to display HTML elements with JavaScript (by writing a script to mark up language, format content, and make content interactive).

To describe request verbs, she has included a chart with the following definitions:

The author uses Atom, a text editor that automatically displays format in different colors to make API calls and responses easier to identify.

When you’re ready to start, create an index.html file in a new directory in Atom that should look like this:


<!doctype html>
<html lang="en">

<head>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">

 <title>Ghibli App</title>
 
 <link href="https://fonts.googleapis.com/css?family=Dosis:400,700" rel="stylesheet">
 <link href="style.css" rel="stylesheet">

</head>

<body>

 <div id="root"></div>

 <script src="scripts.js"></script>
</body>

</html>

You will also create a style.css (to format text content - color, alignment, and borders) to create a grid. This link provides the complete CSS code and the structural CSS looks like this code below:

style.css

#root {
 max-width: 1200px;
 margin: 0 auto;
}

.container {
 display: flex;
 flex-wrap: wrap;
}

.card {
 margin: 1rem;
 border: 1px solid gray;
}

@media screen and (min-width: 600px) {
 .card {
   flex: 1 1 calc(50% - 2rem);
 }
}

@media screen and (min-width: 900px) {
 .card {
   flex: 1 1 calc(33% - 2rem);
 }
}

Once you have HTML and CSS set up, you can make scripts.js to make API calls.

How to Connect to the API

The Studio Ghibli documentation is here and it has been developed to make calls (with HTTP verb requests in CRUD: create, read, update, and delete) that display JSON responses (and will give you the data you’re asking for - in this case, names of films produced by Studio Ghibli). You’re working with JavaScript, but the API is also accessible through PHP, Ruby, Python and additional programming languages.

How to Obtain the API Endpoint

Go to the films section, and see the URL of the endpoint you will use. It says GET /films. When you click it, you will see an array (arrangement) of objects in JSON format. Make sure you have a JSON Viewer. Here’s one for Chrome browser and here’s another for Firefox. JSON is a format that returns data from server to browser. When you make API calls, JSON answers with data. If you want to learn more, read all about JSON (JavaScript Object Notation) here.

How to Retrieve the Data with an HTTP Request

To open a connection to the API, you will use XMLHttpRequest objects, useful to make verb HTTP requests. GET is the verb that you will use, along with the URL of the endpoint.

Here’s how the code looks:

scripts.js

// Create a request variable and assign a new XMLHttpRequest object to it.
var request = new XMLHttpRequest();

// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'https://ghibliapi.herokuapp.com/films', true);

request.onload = function () {
 // Begin accessing JSON data here
 }
}

// Send request
request.send();

How to Work With the JSON Response

Once you have received an answer from JSON (or response from the GET HTTP verb), you will convert it to JavaScript, because that’s the language you’re working with. JSON.parse is what you will use to create an array (arrangement) of JavaScript objects. Parsing means analyze language sentences - or syntax to make the words readable from the file and make it usable to display data you can recognize in a response.

// Begin accessing JSON data here
var data = JSON.parse(this.response);

data.forEach(movie => {
 // Log each movie's title
 console.log(movie.title);
});

A successful response 200 OK, should display the titles of Ghibli films. If there’s a 404 error (like a broken URL), the author provides code to deal with failed requests.

How to Display the Data

If you want to make the project interactive, you will use a DOM that serves as an API that communicates with HTML in JavaScript. DOM means document object model and you can learn more here.

Since your final project should display a logo with multiple card elements for each Ghibli film, you will use CSS to format headings and paragraphs.

Using essential CSS, should look like this:

After describing a step by step in the tutorial, here’s how the final script.js should look:

scripts.js

const app = document.getElementById('root');

const logo = document.createElement('img');
logo.src = 'logo.png';

const container = document.createElement('div');
container.setAttribute('class', 'container');

app.appendChild(logo);
app.appendChild(container);

var request = new XMLHttpRequest();
request.open('GET', 'https://ghibliapi.herokuapp.com/films', true);
request.onload = function () {

 // Begin accessing JSON data here
 var data = JSON.parse(this.response);
 if (request.status >= 200 && request.status < 400) {
   data.forEach(movie => {
     const card = document.createElement('div');
     card.setAttribute('class', 'card');

     const h1 = document.createElement('h1');
     h1.textContent = movie.title;

     const p = document.createElement('p');
     movie.description = movie.description.substring(0, 300);
     p.textContent = `${movie.description}...`;

     container.appendChild(card);
     card.appendChild(h1);
     card.appendChild(p);
   });
 } else {
   const errorMessage = document.createElement('marquee');
   errorMessage.textContent = `Gah, it's not working!`;
   app.appendChild(errorMessage);
 }
}

request.send();

With the full CSS styles, here how your project will look. 200 OK! Congrats!

 

Original Article

How to Connect to an API with JavaScript

 

Comments

campaign-support

I am running a simple node.js code to authenticate the user to ALM 11.00. It was working 2 days back and now it fails to return the session-token