Understanding APIs and the Basics of Using Them

Introduction

Currently, I am learning a lot about APIs in my Bootcamp I am taking, so I thought it would be helpful to show you the importance and opportunities of an API. API stands for Application Programming Interface which is just a fancy way of saying computers communicate with each other in order to grab information for your projects. For a web developer using an API is a great way to get information and present it to the DOM for users. In order to understand it more let's discuss the steps in using an API in your project!

Steps of using an API

From my understanding, the basics of using an API are only a couple of steps: calling the API, Formating the API for your app, and figuring out what to do when an error happens.

Calling an API

To call an API you need to know the link to call from. There are tons of free sites that give links for APIs. Apilist.fun is a great site to get simple APIs for learning purposes. In this blog, let's make a simple app that shows random foxes on our page. I will be using the Randomfox API to build this project. In order to get the information to use in our app, we need to call the API or make a GET request/method. There are tons of methods we can use for APIs but for now, when we make a GET request we are grabbing info from a website to use on our site. To learn more about HTTP methods go here. To make a GET request in JavaScript we use the fetch key. To make our site the code would look like this.

const fox = document.getElementById('fox')
const backupImg = {
  image: 'https://randomfox.ca/images/47.jpg',
  link: 'https://randomfox.ca/?i=47',
};

async function getFox(){
    const response = await fetch('https://randomfox.ca/floof/?ref=apilist.fun');
    const data = await response.json()
    return data
}

This code snippet here is grabbing the info from the RandomfoxAPI, turning it into JSON, and returning the data to be used. You may be wondering what does the Async and awaits do, but to save time (may make a post about those) the async and await keywords allow us to have our function progress until our data is grabbed and turned into JSON. I may be butchering it but I don't want this post to go into the details of what asynchronous Javascript is. Now that we have returned our data we can use and put it into the DOM.

Formating the Data in your App

We have now grabbed the info we need to get our cute foxes, we can now create a function to display them on our DOM! But before doing that let's actually look and see what our getFox function is returning back.

Object
image: "https://randomfox.ca/images/20.jpg"
link: "https://randomfox.ca/?i=20"

This object of an image and link of the fox is what gets returned back in our function, and with this knowledge, we are able to grab the pieces we need to give our image tag a source!

getFox().then(item => {
    fox.setAttribute('src', (item.image))
})

What this code snippet above is doing is, grabbing the fox data from our getFox function and then it setting the src attribute of the image that has the ID of fox. The .then method allows us to dictate what will happen after the getFox function has done its job. We use a callback function in the .then so we can reference the item/items and their properties so we can use them in the DOM. Since the Fox API returns back an object with Image and Link properties we use the dot notation item. image to grab the image link to place in our src for our image tag. Now you should have a random cute fox picture every time your refresh your page! But what happens if the API goes down or an error happens? No worries! we are able to have a back picture if that happens through the use of error-catching!

How to Catch Errors

Catching errors for an API is a safeguard for when the service is no longer in use or some sort of random error happens to your internet or on the server side. If this happens, we can prepare for it to load our app still default image or tell the user something wrong has happened. For the purpose of our app, we will have a default picture of a fox pop with a message that an error has happened and try again later.

getFox()
  .then((item) => {
    fox.setAttribute('src', item.image);
  })
  .catch((err) => {
    alert('Something went wrong! Enjoy this picture of a fox instead!');
    // set up default image
    console.error(err);
    fox.setAttribute('src', backupImg.image);
  });

As you can see, we added the .catch(err) method to allow us to catch if an error happens, long that error to our console, and then have us set up a backup image to send to them DOM. Of course, you can decide what will happen if the user happens to have an error with the API but a good starting point is to have a backup plan if your API decides to not work.

Conclusion

And there you go, we now have a cute website that allows us to have random pictures of foxes! This is just the intro to what you can do with APIs. Currently, I am making a weather forecast app that reads the next 16 days as well as the next 48 hours in the city I live in, which has been a blast to make! I also have started to make a Magic the Gathering Collection app based on an MTG API, so if you can think of it there probably is an API of it to build your dream app! I hope I was able to help you understand the power of APIs and teach you a little about how to use them. I would highly appreciate a follow to my blog or to any of my social media: Twitter Github.

Ps. Sorry for the big gap in between my recent post to this one. I have been super busy with work recently and have completely forgotten to add my posts. I have a few drafts churning so be on the lookout for more content from me!