The world of developer APIs (Application Programming Interfaces) has collided with the world of online learning, and the results are very exciting. xAPI is just one example of marrying the power of APIs with online education. Understanding APIs may lead to more educational usage and new educational applications.

In this tutorial we’ll discuss why APIs can be important for digital learning, and then we’ll construct an API using a web browser and JavaScript code.

Over the last decade, application architecture that includes APIs has become very popular. Known as service-oriented architecture, modern application architecture including APIs has been applied to every type of software development. APIs allow us to connect systems through an agreed-upon protocol that is vendor and language neutral. In development, APIs have been used numerous ways to connect systems that have never been able to talk to each other before.

How about a little translation into everyday terms?

How are APIs used in the real world?

One of the most common applications of APIs and the service-oriented architecture is obtaining real-time information from an outside source. Living in the New York area, I use public transportation almost daily. However, I live in the Connecticut suburbs, not the city core, so trains are less frequent. I use a range of applications to check transportation status and schedules. Since this information can change moment to moment, a schedule database stored on the applications would be out of date immediately. Enter APIs.

The Metropolitan Transit Authority has an extensive API that allows any application to access current API data (Figure 1). Schedules, delays, emergencies, station information, and even point-to-point directions can be provided by the API. The API is open for any developer to use, as long as they obtain a key that authorizes their application. The key is provided at no cost.

By opening their API to any developer, the Metropolitan Transit Authority catalyzed the development of dozens of apps that provided information about the New York transit system.  Via these apps, millions of transit riders like me can obtain up-to-date information about the extensive network of trains, subways, and buses running through the New York metropolitan area.

 

Figure 1: The Metropolitan Transit Authority offers an API with up-to-the-second data about New York transit

ALT TEXT: The Metropolitan Transit Authority offers an API with real-time data about New York transit

The WeatherSTEM API is an education application designed to give educators tools to teach about weather, using real-time weather data (Figure 2). All that’s required is an API key, which is provided free by the API sponsor.

Although training using real-time data can be more engaging and immersive, before the emergence of APIs it was often too difficult or costly to engage with real-world, current data in training environments.

 

Figure 2: Weather information provided by the WeatherSTEM API

ALT TEXT: Weather information provided by the WeatherSTEM API

To get a feel for the sheer number of APIs currently available, check out the ProgrammableWeb directory. It is the largest online directory of APIs, and allows both search and categorical exploration (Figure 3).

 

Figure 3: ProgrammableWeb.com lists hundreds of APIs available for public or subscription usage

ALT TEXT: ProgrammableWeb.com lists hundreds of APIs available for public or subscription usage

You might be surprised to learn that many applications that you use every day have associated APIs. Google Maps and the Google Places APIs are two of the more popular APIs used by thousands of apps on a daily basis.

Access an API with a web browser

Believe it or not, all you need to access an API is a web browser. APIs use the HTTP protocol to communicate. This is the same protocol that is used by the World Wide Web. We can actually test an API using our web browser. First, we need to create a URL and query string that will contact the API.

Let’s use the Quotes on Design API. Simply type the URL for the API endpoint into your browser: http://quotesondesign.com/wp-json/posts

You may be surprised by the result displayed in your browser. Your result will appear similar to the code in Figure 4.

[{"ID":2481,"title":"Laura Mallonee","content":"<p>Photographing something is a way of possessing it. It confirms your connection to places and objects once distant and remote, making the world slightly smaller and less alienating.<\/p>\n","link":"https:\/\/quotesondesign.com\/laura-mallonee\/","custom_meta":{"Source":"<a href=\"https:\/\/www.wired.com\/story\/why-all-travel-photos-are-the-same\/\">article<\/a>"}}]

Figure 4: The result of the query sent to Quotes on Design

The API result looks like a mess but is actually a JavaScript object in the JSON format. If you look carefully you can see the content, a quote from Laura Mallonee about photography.

Let’s change our API request so that we get 10 quotes back instead of just one. Type the following URL in to your browser, all on one line (Figure 5):

http://quotesondesign.com/wp-djson/posts?
filter[orderby]=rand&filter[posts_per_page]=10

Figure 5: URL request

We’ve added a query string to the URL. The query string indicates that we’ll receive the quotes in random order, and we want to receive 10 quotes per page. When you receive the result in the browser, you’ll see 10 separate results in the JSON code.

Developing an API-based application using JavaScript

Let’s conclude by developing a full application using the JavaScript programming language. We’re going to use the OMDB API, which has information about movies (Figure 6).

 

Figure 6: The Movie Monster Application uses the Open Movie Database (OMDB) API to obtain movie information

ALT TEXT: The Movie Monster Applications uses the OMDB API to obtain movie information

Step 1: Generate and store your API key

Begin by obtaining an API key. The API key identifies your specific app and allows requests to be traced back to you. The key provides a layer of security, and I’d caution you about making your key public. You can generate your key for free by providing your email at http://www.omdbapi.com/apikey.aspx.

Open a new text document. We’ll save your API key in this document, which will have only the following line of code (Figure 7):

const apikey = "Your API Key";

Figure 7: Key code

You’ll replace the words “Your API Key” with the API key provided by OMDB, being sure to place the key between the quotes.

Save this file as key.js. (You might want to create a folder in which you’ll store all of the files related to the API application we’re developing.)

Step 2: Set up your file

Create a new, blank text file and save it as movies.html. It will need to be in the same folder as your key.js file. Begin by creating the application frame in HTML and JavaScript (Figure 8).

<!DOCTYPE html>
<html>
<head>
    <title>Movies!</title>
    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:300,300italic,700,700italic">
    <link rel="stylesheet" href="http://cdn.rawgit.com/necolas/normalize.css/master/normalize.css">
    <link rel="stylesheet" href="http://cdn.rawgit.com/milligram/milligram/master/dist/milligram.min.css">
    <style>
        #container{
            margin: 10px;
        }

        img {
            float: right;
        }
    </style>
</head>    
<body>
</body>
</html>

Figure 8: The API frame (movies.html)

Here we have our HTML basic document structure to contain the application. The link elements link the application to the Milligram CSS library for styling. (Instead of typing these, I’d recommend you copy them directly from the Usage section of the Milligram page at https://milligram.io/.)

Following the links to Milligram, we have two CSS style rules that will be applied to our user interface which we’ll create next.

Step 3: Create the UI

We’ll create the simple user interface next. The interface needs to obtain a movie name from the user and display the results provided by the API.

Just after the opening body tag, let’s add the following code for our user interface. (Figure 9)

<div id="container">
<h1>Movie Monster</h1>
<label for="movieName">Movie Name</label>
<input type="text" id="movieName"/>
<button id="btnGetMovieInfo">Get Movie Information</button>
<div id="result"></div>
</div>

Figure 9: This is the code for your user interface

You can see the components in the HTML if you test the file in your browser at this point. (Figure 10). The logical division identified as “result” is empty at this point. We’re reserving this space in our user interface for the result that will be produced by the API.

 

Figure 10: The result of testing the code

ALT TEXT: The result of testing the code

Step 4:  Add the JavaScript

The JavaScript is the heart of this application. The JavaScript will communicate with the API and then parse the JSON that’s returned and use that to display a result to the user.

After the last closing div element carefully type in the code in Figure 11 (or copy and paste it).

<script src="key.js"></script>
<script>
    let theButton = document.getElementById('btnGetMovieInfo');
    theButton.onclick = function(){
        let movieName = document.getElementById('movieName').value;
        let Url="http://www.omdbapi.com/?apikey=" + apikey + "&t=" + movieName;
        fetch(Url)
        .then(data=>{return data.json()})
        .then(res=>{displayResult(res)})
    }
    
    function displayResult(res)
    {
        let out = "<h2>" + res.Title + "</h2>";
        out += "<img src='" + res.Poster +"' />";
        out += "<p>Year: " + res.Year;
        out += "<p>Cast: " + res.Actors;
        out += "<p>Plot: " + res.Plot;
        document.getElementById('result').innerHTML = out;
    }
</script>

Figure 11: This JavaScript will return the result

Note: The code is using the ES6 JavaScript standard, which may differ slightly from older versions of JavaScript with which you may be familiar.

The first line links to our key file so that the key we stored earlier can be accessed. We next deal with the button in the user interface. We only want the API request to occur after the user presses the button. The function associated with the button click is what actually executes the API request.

After getting the movie name the user typed from the user interface, the program creates a URL that will contain the proper query string to communicate with the API. In this case, the URL follows this pattern: http://www.omdbapi.com/?apikey=[YouAPIKey]&t=[MovieTitle]

The movie title and the API key are inserted into the URL. The API will send back JSON data to the application. API communication is facilitated by the fetch function. The data that comes back is eventually stored in the variable res and passed to the displayResult() function, which formats the JSON.

The JSON data that is returned by the API looks similar to Figure 12.

Actors: "Chris Evans, Hayley Atwell, Sebastian Stan, Tommy Lee Jones"
Awards: "3 wins & 46 nominations."
BoxOffice: "$176,636,816"
Country: "USA"
DVD: "25 Oct 2011"
Director: "Joe Johnston"
Genre: "Action, Adventure, Sci-Fi"
Language: "English, Norwegian, French"
Metascore: "66"
Plot: "Steve Rogers, a rejected military soldier transforms into Captain America after taking a dose of a "Super-Soldier serum". But being Captain America comes at a price as he attempts to take down a war monger and a terrorist organization."
Poster: "https://m.media-amazon.com/images/M/MV5BMTYzOTc2NzU3N15BMl5BanBnXkFtZTcwNjY3MDE3NQ@@._V1_SX300.jpg"
Production: "Paramount Pictures"
Rated: "PG-13"
Ratings: (3) [{...}, {...}, {...}]
Released: "22 Jul 2011"
Response: "True"
Runtime: "124 min"
Title: "Captain America: The First Avenger"
Type: "movie"
Website: "http://captainamerica.marvel.com/"
Writer: "Christopher Markus (screenplay), Stephen McFeely (screenplay), Joe Simon (comic books), Jack Kirby (comic books)"
Year: "2011"
imdbID: "tt0458339"
imdbRating: "6.9"
imdbVotes: "623,862"

Figure 12: The JSON returned by the inquiry

We’ll pick out just a few elements to display to the user. In the displayResult() function we pull a few data points out of what has been returned by the API and create the output that the user sees.

Step 5:  Test Your Application

Once you’ve got all the code entered and saved, it’s time to test your application. Run the HTML file in your browser (Figure 13) and test. If it doesn’t work, debug the file to ensure your code is correct and try again.

Congratulations on writing your first API application!

<!DOCTYPE html>
<html>
<head>
    <title>Movies!</title>
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:300,300italic,700,700italic">
    <link rel="stylesheet" href="http://cdn.rawgit.com/necolas/normalize.css/master/normalize.css">
    <link rel="stylesheet" href="http://cdn.rawgit.com/milligram/milligram/master/dist/milligram.min.css">
    <style>
        #container{
            margin: 10px;
        }

        img {
            float: right;
        }
    </style>
</head>    
<body>
<div id="container">
<h1>Movie Monster</h1>
<label for="movieName">Movie Name</label>
<input type="text" id="movieName"/>
<button id="btnGetMovieInfo">Get Movie Information</button>
<div id="result"></div>
</div>
<script src="key.js"></script>
<script>
    let theButton = document.getElementById('btnGetMovieInfo');
    theButton.onclick = function(){
        let movieName = document.getElementById('movieName').value;
        let Url="http://www.omdbapi.com/?apikey=" + apikey + "&t=" + movieName;
        fetch(Url)
        .then(data=>{return data.json()})
        .then(res=>{displayResult(res)})
    }

    function displayResult(res)
    {
        let out = "<h2>" + res.Title + "</h2>";
        out += "<img src='" + res.Poster +"' />";
        out += "<p>Year: " + res.Year;
        out += "<p>Cast: " + res.Actors;
        out += "<p>Plot: " + res.Plot;
        document.getElementById('result').innerHTML = out;
    }
</script>
</body>
</html>

Figure 13: Complete application code