HackerNews: Learn the “new” way to consume APIs with JavaScript

Understand fetch, then, and catch

Jared Moats
7 min readNov 26, 2018

--

Consuming APIs is one of the easiest ways to get and use data for your web applications. (If you don’t know what an API is, you can find a great article about it here)

Utilizing a third-party API in JavaScript used to take more lines of code than necessary. Now, it’s made much more simple with the “fetch” method.

Today we’re going to build a simple clone of the website Hacker News with the free News API. With this API we’re going to be retrieving the top technology news headlines and displaying them on our own local website.

Disclaimer: Before you continue through this tutorial, you need to make sure you’re familiar with the basics of JavaScript, including objects, control flow, function arrow expressions, and DOM manipulation.

First Steps

First thing’s first. Head to the News API website provided above and make a free account. This will give you access to a free API key, which will allow you to access the API’s data. We’ll need it later.

Next, we’re going to set up our HTML and CSS documents. Name the files “index.html” and “style.css”. The code you need for each is below.

Our HTML file is pretty simple. In the <head> tag we’re linking to a Google Font called Fjalla One. We’re also linking to our stylesheet.

In our <body> tag we’ve designated a <main> section of our HTML document. Within it, we’ve created an unordered list with list items containing some headlines I pulled from NBC when I was writing the code.

And, finally, at the end of <body>we link to the JavaScript file we’ll be using for our API magic.

The CSS file is also pretty straight forward. I’ve added some basic positioning and styling so our webpage doesn’t look completely ugly. It’s still not gorgeous, but hey, feel free to make it as pretty as you want after we’re all done!

One final thing to note. Look at our HTML file again. Remember the list items we made? We’re not actually going to be keeping these when our program is complete. We’ll use JavaScript to create list items for us and add them to our HTML document. Right now, we just added them manually to do that CSS styling. Because of that, we know what our final product will look like even before we pull from the API.

That’s all the housekeeping stuff. On to the JavaScript!

JavaScript Setup

Go ahead and remove those list items from your HTML file. JavaScript will do the heavy lifting from here on out.

Now hop over to your JavaScript file (make sure it’s named script.js since that’s we’ve linked to in our HTML document).

Before we start coding, here’s the roadmap for what we’re going to accomplish.

First, we’re going to store our unordered list in a variable so we can add the list items to it later.

Second, we’re going to store a URL from the News API into a variable. This will let the fetch method know where to get its data from.

Third, we’re going to use then to return the data we retrieved, and use then again to retrieve the headline and links we want and then add it to our unordered list.

Finally, we’ll use catch to log to the console any errors that occur (but if we do this right, we’ll be error free!).

Alright, step one. Let’s store our unordered list in a variable for later.

const storyList = document.querySelector('ul');

Next, we need to store the URL we’ll use for the fetch method. Remember that API key I had you sign up for? You’ll need that now. It’ll be attached to the end of our URL.

Now, the URL we need to use to get technology news headlines can be found in the News API documentation. It’s going to look like this: https://newsapi.org/top-headlines?category=technology&apiKey=<yourAPIKey>

Your API Key should be where I designated at the end of the URL.

Alright, let’s store that in a variable to use with fetch.

let url = "https://newsapi.org/top-headlines?category=technology&apiKey=<yourAPIKey>"

Fetch, Then, and Catch

Now this is where things get fun.

We’re finally going to do what you came here for. It’s time to consume an API.

We’re going to “consume” (or retrieve) the APIs data with the fetch method. It’s really simple. You ready?

Yup, that’s it. Not as scary as it’s made out to be, right?

However, now that we have the data, we need to do something with it. We do that with the then method, which we append to fetch . It looks like this.

We have access to our data in the r parameter we’ve included in our arrow function expression. Now we can do stuff with it, and we actually have several options. But the option we need is the json() method. Add return r.json() inside of your then() method. Your code should look like this:

Through the URL we stored in the url variable, we’re accessing a .json file that contains the data we need. “JSON” stands for “JavaScript Object Notation”. A JSON file is a file of JavaScript objects.

But when we access a JSON file, we don’t immediately have access to the objects within it. That’s because the file we’re retrieving, as with most (if not all) API JSON files, is written entirely as a string.

So, when we use return r.json(); , we’re returning the JSON file as a workable array of objects.

Now, we need another then method, and we’ll have another function arrow expression within it. We’ll name the parameter for our function “jsonData”, because now we’re going to be working with the array of objects we just returned in the previous then statement.

Your code within fetch should now look like this:

If you’re familiar with objects, the rest of this is going to be fairly straight forward.

If you didn’t look at the News API Documentation, go back and take a look at it. Under the “Top Headlines” section, you’ll see what our object(s) looks like, as well as the key/value pairs associated with it.

Now, remember that our goal is to display a list of news headlines that link to their respective articles.

You’ll see in the documentation that the object article contains plenty of information, including nested objects with the articles’ URLs and titles. So inside our newest then method, let’s store the articles object into a variable. That’ll make accessing the nested objects within it easier.

let theArticles = jsonData.articles;

Now that we have the articles stored in this variable, we need to loop through each story, retrieving each individual article’s title and URL, storing them in a list item, and then appending them to the unordered list in our HTML document.

We’ll do that with a forEach loop.

Working in the loop now, let’s create that list item.

let storyHeadline = document.createElement('li');

Now that we have the list item created and stored in a variable, we can add to the HTML of the list item to contain the article’s title and link to the story.

storyHeadLine.innerHTML = <'a href="' + story.url + '">"' + story.title + '"' + "</a>";

Now that that’s taken care of, we just need to append our list item to the unordered list in our HTML document. Remember, we stored the unordered list in the storyListvariable. Here’s the code to do this:

storyList.appendChild(storyHeadline);

That completes our final then method. Here’s what you should have within fetchso far.

Finally, to make everything complete, we just need to finish off fetch with the catch method. This is used to handle any errors that occur (such as if fetch couldn’t connect to the API).

Append this to fetch:

And voila! Our Hacker News project is complete.

Here’s a CodePen with our final documents:

(You probably notice there’s no story list under the results tab. I can’t have you stealing my API key, now can I?)

If CodePen isn’t your thing, you can find all the files for this tutorial on GitHub.

Conclusion

Congratulations! You just used JavaScript to consume an API and make a simple clone of Hacker News.

This was only a simple introduction to consuming APIs. If you want to read more about consuming APIs with JavaScript, Sara Vieira over at Scotch.io wrote a fantastic introduction to using fetch .

Tania Rascia (a developer I adore) wrote about how to connect to an API with the “old” way. Check it out.

What do you plan to do with APIs in the future? What projects are you working on now? What’s some other JavaScript topics that might confuse you? Let me know in the comments!

--

--