Using JavaScript to Fetch Data With APIs | by Andrew Stahl | Jun, 2022

Great beginner guide to APIs with an easy-to-follow real-world project.

Title Image; Today’s Topic: Fetch Requests with API


  • Introduction to APIs
  • Introduction to fetch requests
  • Overview of a project that leverages this functionality: a single-page application that produces a date for any US holiday and grabs a fact for that date in history.

What is an API?

If you are a web developer, knowing how to work with an API is a crucial skill in data handling. API stands for Application Programming Interface. It allows two computers to connect to each other and transfer data. They also makes it really easy to pull data into your application that you do not store locally.

For example, if you are building a website and you want to pull in weather information or the latest stock prices, you can choose how to handle that. You can download all that data onto your own servers and have your website connect to them, which would require you to have enough space on your servers to handle that data and you would need to continuously update it as well. The other option would be to find a company or database that has this data and has API functionality that allows you to pull, or fetch, data into your application.

There are a couple of caveats to using APIs that you should be aware of:

  • They are not always free, so in some cases, you need to have a paid membership to access these APIs. Your membership might allow you a certain number of data pulls per day/week/month/year, so you must confirm that before your build-out.
  • Pulling data from another remote server might take a bit longer than pulling data from your own server. With that latency, you should factor that into how your webpage loads so you can still have most of your functionality populate (an average user will only wait 3 seconds for a page to load before moving on)

APIs are a pretty meaty topic, but we will demonstrate how they can work at a base level. I have developed a simple single-page application that utilizes two free APIs to pull data on historical/future holidays.

Let’s dive in!

The project I built will allow the user to pick a US holiday and a year and produce the day for that holiday and a fun fact.

To do this, I used two free APIs, Nager.Date and Wikipedia. There is also a button that allows the user to see how many days are left until we reach that holiday (assuming it is in the future).

I have included a quick visual of the functionality of the page before we dive into the code:

GIF displaying functionality of the project

I need to fetch data for my website in a few different ways:

  • When the page loads, I need to use the Nager API to populate the dropdown for holidays (this is better than hard-coding the days in because I will always have an up-to-date list of holidays instead of the list becoming stagnant over time)
  • After the user submits the holiday and year, I need to use the Nager API to pull in the appropriate date for that holiday.
  • After that date is populated, the site will automatically fetch data using the Wikipedia API to pull a fun fact for that day in history.

To start building the code, I need to lay out the different functions to make it happen. I also need to add event listeners onto elements on the webpage so the application knows when to fetch data.

First Fetch

Focusing on them one at a time, let’s first look at what we need for the fetchHolidays function. Here’s the code that we’ll break down line by line:

I left portions of the code out because I want this blog to focus primarily on fetching API data. For more information on the rest of the code, you can visit my Github repository for this project.

Now let us start breaking this down:


When communicating with an API, you can use a “fetch” request. You can see that I am making a request to fetch data for US holidays in 2022 (you can change both the year and the country code to fetch other holidays).

When you do this, you are calling the API and what you will get in return is not the data for those parameters but a promise to return that data eventually.

This return value is important because it will dictate how you should write the rest of the code for this request.

.then(function(response) {
if (response.status !== 200) {
console.warn("Looks like we didn't get a good request. Request
Code: " + response.status);

return response.json();

Let us take this line by line.

First, you can see that we start off with using .thenwhich follows thefetch request and tells the computer, “fetch the data, then when you receive a response for that data, run the next bit of code.”

The only input for a .then statement is a function. In this case, I’m running a function that checks what the response has been for that fetch request.

There are different codes for different types of responses, but the only one we’re interested in is a 200 response, which means that it was successful (for more details on HTTP response codes, visit MDN Web Docs for HTTP response status codes).

If we don’t get a 200, that means that the fetch request didn’t quite reach or return what we wanted, so we’re just going to put this warning in the console on cancel out of the function with a “return” statement.

If we do get a 200 response status code, we are in business! Keep in mind that the returned response from the server will not be in a usable format, so we need to use our handy .json() function to return that response in a JSON format (which we can work with).

.then(data => data.ForEach(holiday => {
//Extra code to grab the holiday select dropdown and add each
//holiday to that select dropdown

Finally, we’re going to daisy-chain another .then because after receiving the response in a JSON format from our previous .thenwe can finally work with this data.

Instead of a regular function() notation, I used an arrow function as the input. You can use regular notation, arrow notation, or a callback function for these .then inputs (more on callback functions in a bit, as they’ll be crucial to the efficiency of our code).

For this function, I’m getting the data from the previous .then statement, which would return an array-like object for this API, and I’m going to iterate over that array to find each holiday.

I won’t post the rest of the code here since that doesn’t have to do with fetch requests, but you can check it out on my Github repository for this project.

Second Fetch

Now we’re going to go through the second fetch request for pulling the appropriate date for the selected holiday/year

You can see that it looks incredibly similar to the first fetch request that we made with minor differences:

  • Instead of using the current year in the first fetch, we’re using the year that the user selected in the dropdown
  • The function after the second .then statement manipulates the data in a different way

Abstracting The First Two Fetch Requests

So how do we follow the DRY method (Don’t Repeat Yourself) and keep our code intact? In comes the callback function! This is a way that we can pass a function as a parameter of another function. According to W3 schools:

A callback is a function passed as an argument to another function…This technique allows a function to call another function…

We can keep the fetch request as a separate function. Once it returns data, we can call the other functions to step in and do what they need to do. The fetch needs to know the year we are fetching and the callback function that needs to be called after the data runs.

Let’s see this in action using the code at the top with this new abstraction:

Third Fetch

The third and last fetch that we make is to Wikipedia to grab a fun fact for that day in history. We could abstract it even further to be included in our other fetchData function, but I’m going to keep this separate.

This function will fire right after the application grabs the date for the selected holiday.

We need to know the month and day to populate the API URL. Here’s a quick breakdown of this code:

  • The fetch is fetching data from the Wikipedia API and returning a promise to provide a response for that data.
  • The first .then contains a quick arrow function that takes the response returned from the previous code and returns the JSON version of that response.
  • The second .then Takes the data, finds how many elements are in that array (which signifies how many facts Wikipedia stores on that day), and then picks a random fact from that list to display.

This fetch layout was much simpler than the previous ones above, which was intentional for the purpose of this blog. There are a few different ways to write it, but they should follow the same structure to produce the intended result.

Leave a Comment