Check out bidbear.io Amazon Advertising for Humans. Now publicly available 🚀

Intro To API's

Intro

The Application Programming Interface is how code/computers talk to each other, and provides an easy way to collect data or services from external sources.

There is a directory of available API’s at: Programmableweb.com

When you make a request to an API, it is similar to making a request to a website. When you make an HTTP request the website sends back HTML, which is data and structure. When we make an API request, the API responds with just data. That data uses a simpler format than HTML. Typically XML or JSON.

XML

XML is syntactically similar to HTML, but does not describe structure or presentation.

<bird>
    <species>Toucan</species>
    <color>Black</color>
    <location>South America</location>
</bird>
<bird>
    <species>Condor</species>
    <color>White</color>
    <location>Africa</location>
</bird>

JSON

JavaScript Object Notation. JSON is syntactically similar to Javascript Objects, but everything is a string.

{
  "bird": {
    "species": "Toucan",
    "color": "Black",
    "location": "South America",
  }
}

Endpoint

The endpoint is the URL that you make an API request to.

Making API Requests

API Requests with Curl

Curl is a terminal command that can be used to make requests in the terminal. You can make both HTTP and API requests using this command. Though it would be less common to make an HTTP request in your terminal since the terminal won’t actually render a page, we can do it.

curl www.google.com

However this will return an incoherent mess of html.

API Requests with Node

To make requests with a Node server you will want to download a package to help with this. The most common is called request.

request()

The primary function this package provides is request(uri, options, callback) and the callback consists of function(error, response, body).

Here is the official sample code:

var request = require('request');
request('http://www.google.com', function (error, response, body) {
  console.log('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  console.log('body:', body); // Print the HTML for the Google homepage.
});

In it’s simplest form you can think of the request like this:

request( what I want, what to do with it )

Most API’s these days require authentication, which is a subject we will get to later. But to get started we want to use API’s that do not require anything more than the request URL. There is an excellent list of API’s available on Github.

We will use the Star Wars API (SWAPI) for our examples. Let’s request all the data available on the planet with id=1

request('http://swapi.co/api/planets/1/', function (error, response, body) {
  console.log('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  console.log('body:', body); // Return JSON string of body content
});

Which returns and logs the following in the console

error: null
statusCode: 200
body: {"name":"Tatooine","rotation_period":"23","orbital_period":"304","diameter":"10465","climate":"arid","gravity":"1 standard","terrain":"desert","surface_water":"1","population":"200000","residents":["https://swapi.co/api/people/1/","https://swapi.co/api/people/2/","https://swapi.co/api/people/4/","https://swapi.co/api/people/6/","https://swapi.co/api/people/7/","https://swapi.co/api/people/8/","https://swapi.co/api/people/9/","https://swapi.co/api/people/11/","https://swapi.co/api/people/43/","https://swapi.co/api/people/62/"],"films":["https://swapi.co/api/films/5/","https://swapi.co/api/films/4/","https://swapi.co/api/films/6/","https://swapi.co/api/films/3/","https://swapi.co/api/films/1/"],"created":"2014-12-09T13:50:49.641000Z","edited":"2014-12-21T20:48:04.175778Z","url":"https://swapi.co/api/planets/1/"}

It’s not formatted nicely, but you can see that we got null for errors, a response code of 200 which is the standard code for success, and we got back a string with data about Tatooine. Nice.

Parse String to JSON Object

Getting the data in the body back is great, but it is all in a string, which makes it difficult for us to pull out parts of that data. What we need to do is parse the data into a JSON Object, and we can do that using Javascripts built in JSON function.

JSON.parse(body);

and we can set that to a variable and then log the variable

request('http://swapi.co/api/planets/1/', function (error, response, body) {
  console.log('error:', error); 
  console.log('statusCode:', response && response.statusCode); 
  
  var parsedBody = JSON.parse(body);
  console.log(parsedBody);

});

Which then returns a nicely formatted JSON Object

error: null
statusCode: 200
{ name: 'Tatooine',
  rotation_period: '23',
  orbital_period: '304',
  diameter: '10465',
  climate: 'arid',
  gravity: '1 standard',
  terrain: 'desert',
  surface_water: '1',
  population: '200000',
  residents:
   [ 'https://swapi.co/api/people/1/',
     'https://swapi.co/api/people/2/',
     'https://swapi.co/api/people/4/',
     'https://swapi.co/api/people/6/',
     'https://swapi.co/api/people/7/',
     'https://swapi.co/api/people/8/',
     'https://swapi.co/api/people/9/',
     'https://swapi.co/api/people/11/',
     'https://swapi.co/api/people/43/',
     'https://swapi.co/api/people/62/' ],
  films:
   [ 'https://swapi.co/api/films/5/',
     'https://swapi.co/api/films/4/',
     'https://swapi.co/api/films/6/',
     'https://swapi.co/api/films/3/',
     'https://swapi.co/api/films/1/' ],
  created: '2014-12-09T13:50:49.641000Z',
  edited: '2014-12-21T20:48:04.175778Z',
  url: 'https://swapi.co/api/planets/1/' }

Refining The Request

Now we can start to pull specific pieces of information out of the response. If we wanted to get just the name and climate we would log the following

console.log(parsedBody["name"]);
console.log(parsedBody["terrain"]);

we would get back

Tatooine
desert

Sub-Categories

If the data was organized into subcategories we can refine our request by chaining the keys. In this sample we will request the titles of all the movies, and then the first movie title (index 0).

request('http://swapi.co/api/films/', function (error, response, body) {
  console.log('error:', error); 
  console.log('statusCode:', response && response.statusCode); 
  
  var parsedBody = JSON.parse(body);
  
  console.log(parsedBody["results"][0]["title"]);
  
});
A New Hope

or if we wanted to loop over the results array and print all the titles we could do the following

for(var i=0;i<parsedBody["results"].length;i++){
  console.log(parsedBody["results"][i]["title"]);
  }
A New Hope
Attack of the Clones
The Phantom Menace
Revenge of the Sith
Return of the Jedi
The Empire Strikes Back
The Force Awakens

Github Repo

Ncoughlin: API-practice

Amazon Ad Analytics For Humans

Advertising reports automatically saved and displayed beautifully for powerful insights.

bidbear.io
portfolios page sunburst chart