DEV Community

Cover image for Consuming API's  with JavaScript for Beginners.

Consuming API's with JavaScript for Beginners.

gbudjeakp profile image Sebastian Gbudje ・7 min read

Credit: The background Images I use are gotten from Storyset
In my last post, I talked about the importance of knowing how your data is stored/presented. If you are new to web development or coding in general, understanding your data structure is key to creating applications. In this post, I will be showing you exactly how this knowledge helps you create apps by building a simple app that gives random information about different countries using the The Country API.

What we are building

Concepts you will encounter

If you are new to coding, there are some concepts you'll see in this post that might not make sense immediately but I'll be leaving links to resources to help you understand them. Feel free to go through them first or just read the post and check them out later. I'll try to give some basic explanations to them in this post but I urge you to read up on them.
1) promises
2) Destructuring
3) The DOM

Things you'll need

1) A text editor
2) Live Server (Don't worry I went around and found some good short videos about installing a Live server for those who don't know how to or who don't have it.) click on your IDE name and it should take you to a video on YouTube that'll teach you how to set up your live server for that IDE.
Visual Studio Code
If you don't find your IDE on the list, try searching it up on YouTube. I selected those three as they are the three popular ones around.

What is an API

I'll leave a resource below that explains in depth what it is but simply put, an API (Application Programming Interface) is a set of rules that allow programs to communicate with each other.
Learn About API's

Let's Begin

I like to keep my projects organized so start by creating a folder on your desktop. You can name it anything. I've called mine "API for beginners" once that's done you can open the folder in your IDE (doesn't matter which one). Create an index.html and app.js file. You should have something similar below.
Alt Text

Setting up the UI (The HTML)

Our HTML page isn't going to have much since the majority of the work will be done in the DOM. We are simply going to have a button, internal CSS style, and an empty div with an id of "template" where our app info will appear. It should look something like this. Style it however you please
Alt Text

Calling and Using our API

Before we can call and use our API, we need to know what it looks like. API's differ in their design. Some take a REST, SOAP, GraphQL architecture meaning that we might need a different approach when trying to use the API. "Hey, Sebastian, what do you mean by REST, SOAP, etc" for this question, I'll leave this here Explanation on the various API architectures. We are going to be calling our API using the fetch API and then console logging the result to the terminal.

  .then(response => response.json())
  .then(data => console.log(data));
Enter fullscreen mode Exit fullscreen mode

code explanation: The fetch API sends a request to the URL/API we provided asking for the information contained in it. The URL/API responds to our fetch request by sending the information. The next line of the code chains a promise that first parses the information the URL/API sent us and we add one more promise that sends the information to the console.log. "HOLD UP Brother, Hold UP!!!!". Yes, I understand that's a lot to take in, so let me break it down. When we request for the data from the URL/API, the data is sent in a JSON format (there are other formats like BSON) we then use the response.json() to change it into a regular JavaScript data type and then chain a promise that console.logs it. The .then() is the promise here. Think of it as saying "After you do task A, then move to task B then to task C". You can chain as much as you want. Now that we know what's inside that URL/API, let's pick the things we need for our application. We’ll need the name of the countries, the currencies, the region, the languages, and the population

Setting up our app.js

We'll start by adding a click functionality to our button:

const myButton = document.getElementById('fetch');
myButton.addEventListener('click', fetchInfo);
Enter fullscreen mode Exit fullscreen mode

next we'll call the API and parse it before moving it to the displayUi function that'll process and render it to the UI.

function fetchInfo () {
    .then(response => response.json())
    .then(jsonObj => displayUi(jsonObj))
    .catch(() => alert('API Could not be reached at this time'))
Enter fullscreen mode Exit fullscreen mode

"What's that .catch()? It is used to handle any errors that occur. say for example the API server is down our app will notify the user instead of just crashing. we are now done with parsing the data so let's move over to the displayUi function.

 function displayUi (country) {
  const { name, capital, languages, currencies, population, region } = country[Math.floor(Math.random() * 150)]
  const template = `
  <h1 id="head">${name}</h1>
  <p id="content"> This is a country with its capital in ${capital}. 
  The language(s) spoken here are ${languages[0].name}. 
The nation of ${name} is 
  located in the ${region} region with a population of ${population} and uses ${currencies[0].name} 
as it's currency</P>
  // did this so I would avoid the process of having a refresh/update button
  document.getElementById('template').innerHTML = template
Enter fullscreen mode Exit fullscreen mode

code explanation: We pass the parsed data into our displayUi function as a parameter. Which is then destructured to get the specific information like the name of the countries, their languages, currencies, etc. Destructuring helps us reduce the lines of code we have to write. If we did not destructure, we would have to dome something like

  const name =;
  const capital =
  const languages = country.languages
Enter fullscreen mode Exit fullscreen mode

we would have to list out each item we wanted to use for our app like that. "Where did you get the name, capital, region, currencies ?" Remember that before we started, we first checked to see what the API data was like. It was stored in an array of objects and if you expanded it, you would see some key pair values like this.
Alt Text
As you can see, some of those keys have values that are arrays and objects, that also have nested objects and arrays. We set the country parameter to random so that we get random countries. Math.floor rounds a number down to its nearest integer while Math.random returns a random number. We combine both Math.floor and random then multiply by 150 so that we avoid getting the same information twice in a row.
The final part of that function simply sets up our UI template. We create some hardcoded sentences and then add the destructured properties to the parts we want to be populated by the API data. So places where you see ${Some name, it could be currencies, capital region, etc}. "Why did you add [0] after the languages and currencies ?" Remember what I said about the way your data is stored will determine how you use it. If you take a look at languages and currencies keys, their values are stored in an array of objects. Since some countries have more than one spoken language and more than one currency, We specify that we want the language in the 0 index of the array which would be the first object, and then use .name to get the key that holds the name of the language. That way even if a country uses 100 languages, we'll just pick the first one and display it. The last line of the function simply attaches our template variable to the id and our application data is displayed wherever that id is located on our HTML. Now that we are done, open up your application using a live server and try it out. If you get an error saying "fetch is not defined", add window in front of the fetch something like this window. fetch() and that should fix it.


This is not the most optimal way to do this. The API could have been narrowed to specific points and used. You can improve on this application but creating a search bar that lets you search for the countries you want or even a drop-down menu to help filter out things you don't want to see. If you notice any errors in this post or anything that isn't quite correct please drop me a comment and I'll get right to fixing it.

Discussion (0)

Editor guide