A is for Application: API Basics

Celeste Layne
Programming for Design Practices
7 min readJun 26, 2020

What is an API?

API stands for “Application Program Interface” and is a service that provides raw data for public use. The term now commonly refers to web URLs that can be accessed for raw data.

APIs publish data for public use. This lesson walks through how to obtain data on the client side and then render it to the web browser.

How is an API Used?

Imagine you’re sitting at a table in a restaurant with a menu of choices to order from. The kitchen is the part of the “system” that will prepare your order. What is missing is the critical link to communicate your order to the kitchen and deliver your food back to your table. That’s where the waiter or API comes in. The waiter is the messenger — or API — that takes your request or order and tells the kitchen — the system — what to do. Then the waiter delivers the response back to you; in this case, it is the food.

Where Do We Find APIs?

APIs are published everywhere. Chances are good that most major content sources you follow online publish their data in some type of serialized format. Here are a few examples:

  1. Weather: https://openweathermap.org/api
  2. NYC Open Data: https://opendata.cityofnewyork.us/
  3. City of Chicago: https://data.cityofchicago.org/
  4. Cooper Hewitt, Smithsonian Design Museum Collections: https://collection.cooperhewitt.org/api/
  5. The New York Public Library Digital Collections API: http://api.repo.nypl.org/

Why Just Data?

Sometimes thats’s all we need. All this information, from all these browsers and all these servers, has to travel through the network. That’s almost certainly the slowest part of the request cycle. We want to minimize the bits. There are times when we just need the data. For those times, we want a concise format.

What is Serialized Data?

All data sent via HTTP are strings. Unfortunately, what we really want to pass between web applications is structured data (i.e., arrays and objects). So, native data structures can be serialized into a string representation of the data.

One of these serialized data formats is JSON:

JSON

JSON stands for “JavaScript Object Notation” and has become a universal standard for serializing native data structures for transmission. It is light-weight, easy to read and quick to parse.

{
"users": [
{ "name": "Carl", "id": 536 },
{ "name": "Heather", "id": 857 }
]
}

Note: JSON is a serialized format. While it may look like an object, it needs to be parsed so we can interact with it as a true Javascript object.

Parsing JSON

JSON is the standard format to orgranise data for servers to send and receive data. It’s so popular that JS has two methods to package it for sending and receiving:

Making an API Call

For our first API call, we’ll use the Google Books API. We’ll create a basic site where users can add books to a reading list by entering their International Standard Book Number (ISBN). Let’s start with a simple HTML form where a user can enter an ISBN, as well as an unordered list where we will add each book the user searches for:

<h1>Search for a book by ISBN</h1>

<form>
<input type="text" id="isbn" name="isbn" value="" placeholder="Please enter an ISBN">
<button type="submit">Find Book</button>
</form>

<ul class="books"></ul>

URLs

Before taking a look at the JavaScript, let’s take a step back and find out how we can access the data for a book using the Google Books API. To access this information, we’ll need a URL where we can find the JSON data for a book that matches an ISBN number. To access this information, we’ll need a URL where we can find the JSON data for a book that matches an ISBN number.

Let’s take a look at the different components of a URL that could be used for an API call:

  • The Protocol: HTTP — or Hypertext Transfer Protocol — is a system of rules (“protocol”) that determines how web pages (“hypertext”) are sent (“transfer”) from one place to another.
  • The Host: This is the domain name for the site. This request will be sent to a Domain Name Server (DNS), which will look up the IP address and find out where the files for that resource are stored. An IP address is a unique string of numbers that helps us locate the correct server.
  • The Port: Internet hosts have a certain number of ports that offer different services. One port could offer HTTP, another could offer mail routing, and so on. HTTP usually runs on port 80 and HTTPS runs on port 443, but this is not always the case. If the protocol is running on the default port (80 or 443), you don’t need to specify a port number. If it is running on a different port, a colon (:) followed by the port number (in this case, 1234) is required to point to that port.
  • The Resource Path: Where the resource (HTML, JSON, PDF, images, etc.) is located.
  • The Query: We can use queries to “filter” the data we find and retrieve certain results.

> image with the Google Books URL

Constructing the URL

We can use string concatenation to add the right ISBN to the URL, and then locate information about that book:

// using concatenation
"https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbnUserEntered
// using string templating
`https://www.googleapis.com/books/v1/volumes?q=isbn:${isbnUserEntered}`

Paste the below URL into your web browser and take a look at the JSON object that is returned:

https://www.googleapis.com/books/v1/volumes?q=isbn:0679775439

You can see that we have an array named “items.” This array contains a JSON object:

{
"items": [
{
"volumeInfo": {
"title": "The Wind-up Bird Chronicle",
"description": "Superimposes the collapse of a marriage over the investigation into recovered war memories and a man's search for his own identity",
"imageLinks": {
"thumbnail": "http://books.google.com/books/content?id=iTt3WN2U8wwC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
},
"previewLink": "http://books.google.com/books?id=iTt3WN2U8wwC&printsec=frontcover&dq=isbn:0679775439&hl=&cd=1&source=gbs_api"
}
}
]
}

Within that object, there is an object named "volumeInfo" that contains information we want to access about the book: a title, description, thumbnail, and preview link.

To access the title in this array, we can use the following syntax:

response.items[0].volumeInfo.title

Getting Data from an API with JavaScript Fetch

Now that we know more about the URL, we’ll use that information to make the API call and receive data. Let’s dig into the JavaScript using a basic fetch request:

fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));

Here we are fetching a JSON file across the network and printing it to the console. The simplest use of fetch() takes one argument — the path to the resource you want to fetch — and returns a promise containing the response. This is just an HTTP response, not the actual JSON. To extract the JSON body content from the response, we use the json() method.

Using Fetch, MDN Documentation
How to Use the JavaScript Fetch API to Get Data by Sara Vieira. Scotch.io

Tutorial — Making an API Call

Let’s take a look at an API that has very clear documentation — OpenWeatherMap — and then practice looking through that documentation and making API calls. In order to use it, please follow these steps:

Instructions

  1. Sign up for a free Open Weather Map account.
  2. Once you’ve signed up, you’re given an API key. Copy that API key and keep track of it somewhere. Create a variable in your JavaScript file to store the key. e.g. let API_KEY = “”;
  3. Go to OpenWeatherMap and scroll down, you’ll see a section that says “API Documentation.”
  4. Construct the URL endpoint that could be used for an API call.
  5. Make sure you’re getting back the URL you need by placing a console.log statement to log the response received from the server.
  6. Finally, write the fetch request to get the full response from the URL endpoint and wrap it in a function called getWeatherData.
const getWeatherData = () => {
// fetch request goes in here :-)
}
getWeatherData()

Codepen Solution

Looking at Documentation

There are no rules governing how to write documentation for an API, so its content is presented differently each time. Knowing how to quickly find key pieces of information is the most important part of reading API documentation.

API Keys

While the majority of APIs are free to use, many of them require an API “key” that identifies the developer requesting data access. This is done to regulate usage and prevent abuse. Some APIs also rate-limit developers, meaning they have caps on the free data allowed during a given time period.

When we click on the “How to Start” link, we are taken to a page that provides us with information on how to get an API key. For security reasons, many APIs require the use of keys.

An API key is like a signature that uniquely identifies a user. This helps APIs keep track of their traffic and monitor any suspicious activity, such as an individual user sending too many requests.

For example, malicious users might try using multiple usernames until they find one that works. Keys can help prevent these kinds of attacks by limiting how many requests one user can make.

OpenWeatherMap’s documentation makes it easy for us to obtain an API key. We simply click the “Sign Up” button and create an account, and then you can get an API key.

To make an API call, we’ll need to add our key to the URL:

http://api.openweathermap.org/data/2.5/forecast/city?id=524901&APPID={APIKEY}

Now that we have our key, let’s look back at some of the other information the API documentation can provide. Spend a few minutes exploring the documentation. See what different types of data you can get from the API.

Exercise #9

Add a feature to your website that changes the background based on the weather e.g. background color, gradient, image, shapes etc.

Codepen Solution

--

--