Consuming API's with JavaScript for Beginners.
Tags: webdev, beginners, javascript
Published: 2021-02-06 22:21:16

Credit: The background Images I use are gotten from [Storyset](https://storyset.com/search?q=Freepik)
<em>In my last [post](https://dev.to/gbudjeakp/how-to-make-applications-from-scratch-without-tutorials-for-beginners-26bg), 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](https://restcountries.eu/rest/v2/all)</em>.

<h1>What we are building</h1>
{% codepen https://codepen.io/gbudjeakp/pen/gOLrWqd %}

<h3>Concepts you will encounter</h3>
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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
2) [Destructuring](https://wesbos.com/destructuring-objects)
3) [The DOM](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction)

<h3>Things you'll need</h3>
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. 
[Sublime](https://www.youtube.com/watch?v=5CinAgQylao) 
[Visual Studio Code](https://www.youtube.com/watch?v=y4qqQeUDCBQ)
[Atom](https://www.youtube.com/watch?v=0Xy3yDDY4IE)
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.

<h2>What is an API</h2>
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](https://www.howtogeek.com/343877/what-is-an-api/)

<h2>Let's Begin</h2>
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](https://dev-to-uploads.s3.amazonaws.com/i/4ipdpogcjfvok43fc43b.png)

<h3> Setting up the UI (The HTML) </h3>
Our HTML page isn't going to have much since the majority of the work will be done in the [DOM](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction). 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](https://dev-to-uploads.s3.amazonaws.com/i/syms3m08b7cszwrk7ndh.png)

<h3>Calling and Using our API</h3>
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](https://api-university.com/blog/styles-for-apis-soap-rest-and-rpc/#:~:text=In%20this%20blog%2C%20we%20study,and%20disadvantages%2C%20commonalities%20and%20differences.). We are going to be calling our API using the `fetch` API and then console logging the result to the terminal.
```javascript
fetch('https://restcountries.eu/rest/v2/all')
  .then(response => response.json())
  .then(data => console.log(data));
```
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

<h3>Setting up our app.js</h3>
We'll start by adding a click functionality to our button: 
```javascript
const myButton = document.getElementById('fetch');
myButton.addEventListener('click', fetchInfo);
```

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. 
```javascript
function fetchInfo () {
  fetch('https://restcountries.eu/rest/v2/all') 
    .then(response => response.json())
    .then(jsonObj => displayUi(jsonObj))
    .catch(() => alert('API Could not be reached at this time'))
}
```
"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.

```javascript
 function displayUi (country) {
  const { name, capital, languages, currencies, population, region } = country[Math.floor(Math.random() * 150)]
  const template = `
  <div>
  <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>
  </div>
  `
  // did this so I would avoid the process of having a refresh/update button
  document.getElementById('template').innerHTML = template
}
```
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 
```javaScript
  const name = country.name;
  const capital = country.capital
  const languages = country.languages
```
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](https://dev-to-uploads.s3.amazonaws.com/i/ztlfpj2d9fdmmkq3vt2z.png)
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.

<h1>Conclusion</h1>
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.