JavaScript with Sean Doyle

Lesson 11: Working with APIs

The Application Programming Interface (API)

The Big 5 Concepts

  1. An Application Programming Interface (API) is a method for one application to interact with another application that protects both applications.
  2. The data application creates a set of commands as URLs ("end points") that allow our apps to request data (GET) and send data to it (POST).
  3. The list of commands and parameters, along with API requirements such as registration, costs and limits, are normally listed in the documentation provided by the data application.
  4. The raw data may need modification when outputting to a web page. For example, a price might need a dollar sign added, a timestamp may need to be converted, or a measurement may need units appended to the text string such as: "litres", "miles per hour", "Celsius", or "tablespoons".
  5. The most common data format for APIs is JSON. JavaScript Object Notation (JSON) is a specialized format of a JS object, but we access its properties just like a regular object. The API data is sent as a JSON object, and its values are held as properties of this object.

Code Samples

//AJAX with the XMLHttpRequest object is a common way to fetch API data by providing a URL ("end point") instead of a local file name.
var apiUrl = "https://jsonplaceholder.typicode.com/todos/1";

xhr.open('GET', apiUrl, true);

//Create a variable to hold the dataset (a JavaScript object)
var APIDATA = xhr.response;
//Paste the URL above into a browser to see what APIDATA would be holding.

//Through the dataset variable, access the API data properties (using dot notation) and output to the web page.
listTitleSpan.innerHTML = APIDATA.title;