An Introduction to APIs

What is an API?

Technically, it stands for Application Programming Interface.

On a day to day basis an API represents a standardized way to send and retrieve data from a remote source. Usually this data is returned as JSON. Typical examples of ways in which you might use an API are:

  • Retrieve recent posts from you Instagram account.
  • Send cart information to a Shopify store after pressing an “add to cart” button. 
  • Retrieve information from Twitter regarding a particular hashtag. 
  • Retrieve weather data for a particular area.

APIs may support sending data to a remote location, and also retrieving data from a remote location. This process is represented in HTTP (Hypertext Transfer Protocol, the protocol your browser uses to send and receive information between servers), using the HTTP verbs GET and POST.  For our exercise we will only be using the GET method to receive data.

You will often need to authenticate yourself when using an API by providing an API key in your request to the service. In our exercise, we will rely on an API that requires you to pass a key in the URL in order to authenticate our request.

Working with JSON objects in JavaScript

var myObject = {}; // Store an empty object in javascript

// Define a variable named "weather", that has a series of key/value pairs.
// Objects can have nested objects within them (wind in this example).
var weather = {
  temperature: 54,
  forecast: 'Cloudy',
  wind: {
    speed: 1,
    direction: 'NW'
  },
  alerts: [
    'thunderstorm warning',
    'potential flooding'
  ]
};

// Refer to properties of an object using dot notation:
weather.temperature // 54
weather.forecast // 'Cloudy'
weather.wind // { speed: 1, direction: 'NW' }

// For nested objects, use dot notation to refer to the nested keys:
weather.wind.speed // 1
weather.wind.direction // 'NW'

// Objects may also contain data stored in an array:
weather.alerts // ['thunderstorm warning', 'potential flooding']
weather.alerts[0] // 'thunderstorm warning'
weather.alerts[1] // 'potential flooding'

Open Weather Map

Today, we will use OpenWeatherMap for testing. Please create an account with the service in order to retrieve your own API key. We will be exposing our API keys to the public – normally you wouldn’t do this, but for testing purposes it should be OK. Just don’t enter any payment information when setting up your OpenWeatherMap account. 

Calling the API

We’ll use jQuery’s $.get function to retrieve data from the weather service. This is a process known as AJAX (asynchronous JavaScript and XML). After our web page loads, we’ll have the ability to query external services for additional data, which we can then use JavaScript to insert into our document and manipulate in whatever way we wish!