Demo: Writing the API Wrapper

An example of writing an API wrapper class for the New York Times API.

Scroll down...

Content

Resources

Comments

This demo shows you how to wrap up an API using JavaScript, complete with all the bells and whistles.

A Basic HTTP Library: Request

The Request library is a very simple HTTP client. You will supply its method with a URL and a callback for processing the response, whether that is an error or JSON. Here's what it looks like to make a basic HTTP request.

const request = require('request')

request('http://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=json', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(JSON.parse(body))
  }
})

If all goes well, we should receive an inspirational quote in JSON format.

{ quoteText: "If A is success in life, then A equals x plus y plus z. Work is x; y is play; and z is keeping your mouth shut. ",
  quoteAuthor: "Albert Einstein",
  senderName: "",
  senderLink: "",
  quoteLink: "http://forismatic.com/en/198af145ad/" }

Did he really say that? That's not his best formula.

The New York Times Example

For this example, we'll create a class to wrap our API. It doesn't have many bells and whistles at this point but we could always refactor it to be more flexible if our use case for the API changed. Using a class here allows us to instantiate the wrapper with our API key—and any other options we'd like to add in the future.

The code below shows the whole API wrapper, plus a basic usage example:

// times_api.js

const request = require('request')

const baseUri = "http://api.nytimes.com/svc/mostpopular/v2"

class TheTimes {
  constructor(apiKey) {
    this.apiKey = apiKey
  }

  mostEmailed(callback) {
    this._sendRequest("mostemailed", callback)
  }

  mostViewed(callback) {
    this._sendRequest("mostviewed", callback)
  }

  mostShared(callback) {
    this._sendRequest("mostshared", callback)
  }

  _sendRequest(type, callback) {
    const url = `${baseUri}/${type}/all-sections/7?api-key=${this.apiKey}`

    request(url, function(error, response, body) {
      if (!error & response.statusCode === 200) {
        callback(JSON.parse(body).results)
      }
    })
  }
}


// Usage

const times = new TheTimes("YOUR_API_KEY")

times.mostEmailed(function(data) {
  console.log(data[0])
})

As you can see, initialization was pretty straightforward. It takes an API key and then runs custom methods which attach that key to each request.

As you can see, the most shared, most emailed, or most viewed stories all call the same pseudo-private _sendRequest method.

Examples

Here's a script that uses this object:

const times = new TheTimes("YOUR_API_KEY")

times.mostEmailed(function(articles) {
  console.log("Most Emailed")
  console.log("=====")
  articles.forEach(article => { console.log(article.title) })
})

times.mostViewed(function(articles) {
  console.log(" ")
  console.log("Most Viewed")
  console.log("=====")
  articles.forEach(article => { console.log(article.title) })
})

times.mostShared(function(articles) {
  console.log(" ")
  console.log("Most Shared")
  console.log("=====")
  articles.forEach(article => { console.log(article.title) })
})

Here's what our output from the above looks like:

Most Emailed
=====
A Quiet Giant of Investing Weighs In on Trump
Trump and Staff Rethink Tactics After Stumbles
My Paris: Seduced by the Past
...

Most Shared
=====
Trump and Staff Rethink Tactics After Stumbles
Why Nobody Cares the President Is Lying
A Quiet Giant of Investing Weighs In on Trump
...

Most Viewed
=====
Trump and Staff Rethink Tactics After Stumbles
Listen to Your Daily Audio Report
Betsy DeVos Confirmed as Education Secretary; Pence Breaks Tie
...

Given the output there, you should be able to figure out how to interface with this class. It works on its own in JavaScript, and you can easily include this object in an Express app to grab data and package it up as object-oriented as possible.



Sign up to track your progress for free

There are ( ) additional resources for this lesson. Check them out!

There are no additional resources for this lesson just yet!

Sorry, comments aren't active just yet!

Next Lesson: Test Yourself: Basic API Interaction