Getting Started with APIs

What is an API? An API or Application Programming Interface is something that a website or online service designs to make some of their data available to the public, for use in applications or other purposes. Most web services have an API – Facebook, Yelp, Twitter… they all have ways to access their public data. You usually have to do something to sign up for access to an API, and then you are granted access credentials to use in your code. You can use APIs to get data, as well as to connect them to applications that you create that use their data.

Open APIs

Some APIs are public and don’t require an authentication process to use them. For example, visit the Dog API. This is a public API about dogs. On it, you can use it to put a random picture of a dog on a website, as well as get info about breeds and sub-breeds.

If you put the url in the address bar of a browser, you will see that it generates a “message” with a different image url each time you refresh the browser.

See the code below. Using the JQuery function $.getJSON, we can make a request for the picture to be used on a website. (JQuery is a JavaScript library. Notice the reference to JQuery from the Google API in the head section). The JQuery function .html is similar to the JavaScript .innerHTML function. The comments explain more of the functionality.

Put the code below in an html file and run it. Each time you refresh you will see a new dog photo!

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<body>

<script>
//getJSON JQuery function that makes an API request
$.getJSON('https://dog.ceo/api/breeds/image/random', function(data) {

//JQuery html method manipulates DOM with img html and source from API
$("#dog").html("<img src=" + data.message + " />")

});
</script>

<h2>Get a Doggie</h2>
<div id="dog"></div>

</body>
</html>

Let’s try another. There is a Star Wars API that also does not require authentication. The documentation describes what you can find in it, but they have json for people, planets and starships. For example, visit https://swapi.co/api/people/1/. This shows all the information available for Luke Skywalker. Use the code below and see it give you the names of 10 Star Wars characters. This code uses a loop to run through the numbers at the end of the url string that increments for each character. It appends, rather than replaces, to the html each time it runs through the loop and concatenates a <br> between each character.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<body>
<script>

for(i=1; i<=10; i++) {
url = "https://swapi.co/api/people/" + i;
$.getJSON(url, function(data2) {

//JQuery append method manipulates DOM with name and a break
$("#sw").append(data2.name + "<br>");

});
}
</script>

<p id="sw"></p>
</body>
</html>

Pretty cool, huh? You can access the values of other keys in the json data. Change the append line to include the “gender” information and concatenate text, as below.

$("#sw").append("Name: " + data2.name + ", Gender: " + data2.gender + "<br>");

Once you learn how to make requests to an API, you can do all sorts of things with the data. Be creative. Here is a list of APIs that do not require authentication.

APIs Requiring Authentication

Most APIs require a developer to sign up and use authentication. Let’s look at the Open Weather API. This app provides a wide range of weather information. The Guide page will instruct you on how to sign up for a free API Key which gives you access to some of their services. It should only take a few minutes before your API key is activated. You will receive a confirmation email.

Let’s look at the Austin weather forecast for today. In the browser, include the following statement, replacing YOUR_API_KEY with the API Key you received when you signed up for Open Weather. The “units” variable in the url string changes the temperature to Fahrenheit.

https://api.openweathermap.org/data/2.5/weather?q=Austin,us&units=imperial&appid=YOUR_API_KEY

You will see the API information for Austin weather. Let’s use it in a page, as we did above. Include your own api key in the url string. Notice that I have also concatenated the html code for the degree symbol and an F for Fahrenheit. Now you have an updating weather app of the current temperature for Austin!

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<body>

<script>
//getJSON JQuery function that makes an API request
$.getJSON('https://api.openweathermap.org/data/2.5/weather?q=Austin,us&units=imperial&appid=YOUR_KEY_HERE', function(data) {

// creates the url string for the icon. This is info provided by the service, you just have include the reference to your icon
var icon = "http://openweathermap.org/img/w/" + data.weather[0].icon + ".png";
var temp = data.main.temp;

//JQuery html method manipulates DOM with img html and source from API for icon and appends the temp
$("#myweather").html("<img src=" + icon + " />");
$("#myweather").append(temp + "° F");
});
</script>

<div id="myweather"></div>

</body>
</html>

We can make the app a little more sophisticated by adding a dropdown to select a city and launching a getWeather function on the onChange event. It also changes the api url string to concatenate the city variable and handles what happens when a user picks Select a City. See the code below.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<body>

<script>

function getWeather() {
// makes city into a variable
city = document.getElementById("thedropdown").value;
$("#myweather").html("");

//getJSON JQuery function that makes an API request
//concatenates city variable from the dropdown
$.getJSON('https://api.openweathermap.org/data/2.5/weather?q=' + city + ',us&units=imperial&appid=YOUR_KEY_HERE', function(data) {

var icon = "http://openweathermap.org/img/w/" + data.weather[0].icon + ".png";
var temp = data.main.temp;

//JQuery html method manipulates DOM with img html and source from API

$("#myweather").append("<img src=" + icon + " />");

$("#myweather").append(temp + "° F");

});
}
</script>

<h2>Texas Weather</h2>
<select id="thedropdown" onchange="getWeather()">
<option>Select a City</option>
<option value="Austin">Austin</option>
<option value="San Antonio">San Antonio</option>
<option value="Dallas">Dallas</option>
</select>

<div id="myweather"></div>

</body>
</html>

Now that’s more like an app! APIs can get advanced pretty quickly. You would generally not want to include your api key in an html file that could be revealed. Most would store their keys in a server-side document, but this is fine for testing and demonstrating for student projects.

Using an API Console

Some platforms have an API console that you can use to experiment with API calls. Try the Spotify Developer Console. Under Artists, find Related Artists. This would allow you to create a recommendation app for artists similar to others. You need to sign up for Spotify credentials and access to Spotify to get an Artist’s URI (ctrl-Click on artist name in Spotify and choose Share). With those items you can run the query, which is in json format. You can copy the json data and use a json-to-csv converter to convert to a format that can be read in a spreadsheet. You can also use the json in your own application. This works well for data that doesn’t need to be actively updated by the API and simplifies he process of using it. In this example, we will grab the data, analyze it and put it on our own site to use in an app that makes artist recommendations.

Once you have made a call for an artist that you like, generate the json. You can copy that information and use it in the json-to-csv converter . Then you can open that file in Excel and remove any columns you don’t need. We are going to focus on the artist url, name and popularity. I am also going to add a column that indicates which artist this was originally generated from, in the “same” field. Do this for a few bands and create one csv. Then you can go to a csv-to-json converter to get your pared-down json file (find mine here). You will use this json in the data variable in your code. It is an array of objects. No JQuery needed for this example, because we aren’t using the .getJSON method.

The code below reads the artists into the page. This uses a loop to read the name of each band and concatenates a <br>. The += indicates appending rather than replacing the information in the DOM.

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="related"></div>

<script>
data = [include the array you generated with your data here]

for(i=0; i<data.length; i++) {
document.getElementById("related").innerHTML += data[i].name + "<br>";
}
</script>

</body>
</html>

Let’s make our app more interactive and provide a bit more information. Use the code below to add a dropdown that is used to filter the data based on who is selected and additional information about the related artists (url and popularity).

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<select id="thedropdown" onchange="getRelated()">
<option>Select a Band</option>
<option value="old97s">Old 97's</option>
<option value="spoon">Spoon</option>
</select>
<div id="related"></div>

<script>
data = [include the array you generated with your data here]

function getRelated() {
band = document.getElementById("thedropdown").value;
document.getElementById("related").innerHTML = ""
for(i=0; i<data.length; i++) {
if(band == data[i].same){
document.getElementById("related").innerHTML += "<a href=" + data[i].url + ">" + data[i].name + "</a>, " + data[i].popularity + "<br>";
}
}
}
</script>
</body>
</html>

Personally, I’d like this app a lot better if it were formatted in a table. Change the “related” div to a table (<table id=”related”></table>) and replace the code below in your innerHTML statement.

document.getElementById("related").innerHTML += "<tr><td><a href=" + data[i].url + ">" + data[i].name + "</a></td><td> " + data[i].popularity +"</td></tr>";

This should give you a good sense of some of the ways to use APIs. There are many more things you could do to create applications or design interactive elements. Our next exercise will show you how to access Twitter API information using Python.