Making Use of APIs in Your Front End
As a Web Developer there is so much stuff to learn and if you’re anything like me, sometimes you get lost in the sea of things you “need to know”.
But out of all those things you need to learn, there is one thing that will spice up your applications and make you look like an expert developer to potential employers.
That one thing is how to use an API.
Using an API allows you to make any website or web application more exciting and dynamic than what you can accomplish with html,css and javascript by themselves. So in this post, I am going to help you learn more about APIs and how you can use them through a simple project.
In this project we will be making use of the Unsplash API to create an image gallery. Throughout the post, I will be providing commented code snippets as well as an explanation of what the code is doing at each point.
So what is an API?
API is an acronym that stands for Application Programming Interface and according to wikipedia, an application programming interface (API) is a computing interface which defines interactions between multiple software intermediaries.
What that definition basically means is that APIs allow your web application to communicate with other web applications. This “communication” can be best explained with an example specific to the project we are going to build.
For this project, we will be using the Unsplash API to create an image gallery. We are using the API to communicate with Unsplash (Unsplash.com). In this communication, we are making a “request” to Unsplash’s server to get access to some of their images, so we can use them for our image gallery.
The most important part to take note of here is that we are using the API to get access to Unsplash’s images for us to use in our project; what this means is that we can use an API to get data from an outside source which is very cool and very useful.
Getting Started with our Image Gallery
Before we can get started with using the API, we have to set up a basic structure for our project. For this project we will need a code editor to write our code in. I personally recommed the Visual Studio Code editor but you can use any code editor you want to do this.
Open up the code editor of your choice and create a directory (folder) with the title “unsplash_api_gallery”. Inside the directory you need the following three files:
- index.html
- index.css
- index.js
You can look to the picture below for a visual on what it should look like
Setting up the Basic Structure of our page
The content of our web page is going to be made up mostly of images generated in our JavaScript file but we do need to set up a basic structure of our web page using some html and css
Open up the index.html file in the directory and enter the following:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Fancy Car Gallery</title> <link rel="stylesheet" href="index.css"> <script defer src="index.js"></script></head><body> <!-- My header here is just for presentation--> <header> <h1> Fancy Car Gallery</h1> </header> <div id = "img-box"> <!-- I will be populating this div with images from my unsplash api call--> </div> <!-- My footer here is just for presentation-->
<footer> <p id = "footer-text"> <span style = "text- decoration:underline;"> Designed & Developed by :</span> Patrick Pierre</p> </footer></body></html>
In the html code above, notice that there is a section of it that says <div id = “img-box”>
. This part is important because this is the html tag that will contain all of the images that we will get from our call to the unsplash API. The <header></header>
and the <footer></footer>
are used in our html for styling purposes. Lastly all the code inside the<head></head>
will be used to make sure our html document meets with the web’s best practices and to allow our css file and javascript file to be load.
Now open up the index.css file and enter the following:
/* All the flex-related properties are used to help position things on the page */*{
box-sizing: border-box;
}body,html{/*The padding and margin here are 0 so that we don't see any white space around the edges of the header and footer*/ padding:0;
margin:0;
background-color: white;
}body{ display:flex;
flex-direction: column;
flex-wrap: wrap;
}header,footer{ margin:0;
padding:0;
height:200px;
width:auto;
padding: 20px 10px;
background-color:rgba(26,26,26,.7);
display:flex;
flex-direction: column;
justify-content: center;
color:white;}h1{ text-align:center;
font-size:40px;}#img-box{ display:flex;
flex-direction: row;
justify-content: center;
flex-wrap: wrap;
padding:0px;
width: 100%;}#footer-text{ text-align:center;
font-size:25px;}
Since this is project focuses on what we are going to do in our JavaScript code, I won’t get into the specifics of what the css code does but if you want to learn more about css I will provide a great resource you can use at the end of the post.
Making our Request to the Unsplash API
So we’re finally ready to start working with APIs in our JavaScript file…
But before we get into the code there are a few more things I would like to tell you about using the Unsplash API.
In order to use the Unsplash API in JavaScript, you need to learn how to use the Fetch method and you need to register for an API key.
So what is the Fetch Method?
The Fetch method is a method provided by the Fetch API that is built into the browser. It is used to get access to data through the use of the HTTP protocol,which the system used to transfer files throughout the internet.
Below is a snippet of JavaScript code that will show you the syntax of how to make a request using the Fetch method.
const requestUrl = "url of whatever you want to make a request to";fetch(requestUrl)
.then(response => response.json())
.then(data => {
// do something with the data the API has returned
})
Okay now let me explain what is going on in the code above.
In the first line of code we have defined a variable that contains the url of the API we would like to make a request to. In the second line, we started the fetch request with the fetch method. It is important to note that the fetch method takes 2 arguments (the 2nd argument is optional). If we only use one argument the request will default to a GET request; if we use the 2nd argument, we have access to all the other requests types.
So let’s just say we decided to log the result of fetch(requestUrl)
with a valid url as an argument to the browser console using console.log()
. When logged to the console we will get back a promise object. A promise is a special JavaScript Object, that will allow us to receive our data from the fetch request if it is successful or execute some snippet of code if the requested data fails to get back to us.
Since our fetch returns a promise object, we have access to the following three methods:
.then(callback)
which is is used when the promise is fulfilled (success).catch(callback)
which is used when the promise is rejected (fail).finally(callback)
happens on both a fulfilled and rejected promise
In the above code snippet we use .then()
to allow our code to do something with a successful promise. Our .then()
method, and all other methods of promise objects, takes a callback function as an argument. It is considered best practice to use an ES6 arrow function as a callback function so we use it in both of our .then()
methods.
As you might have noticed, we chained two .then()
method onto our fetch request; the reason why we did this is because the result of calling our first .then()
on the promise returned from fetch()
is actually another promise object!
Because our .then()
returns another promise object, we have to use another .then()
on it to get access to our data from our api request.
Lastly I would like you to look at the callback functions inside each of the .then()
method invocations . Inside the first .then()
we put:
response => response.json()
What this does is allow us to get access to our data from the second promise in the form of a JavaScript object.
You need to include this part in your fetch request in order to get back the data you want as a result for you to use in the callback of your second .then()
How do I register for an API key on Unsplash?
Now that we finished covering how to use the fetch method, the last thing we need is to register for an API key on Unsplash’s website. We need an API key in order to make fetch requests to Unsplash’s API.
The API key will provide us with authorization to use Unsplash’s data. In order to get your API key click here, and choose the option that says “register as a developer”. Once you register, you should be given access to your unique API key.
API keys are as important as the password to your phone or bank account so make sure that you do not make your API keys publically available or share them with anyone. What this means is that if you ever wanted to host this project or to use an API in a future website or application, you will need to look into how to hide your API keys properly.
A great resource on how to do that will be provided at the end of the post, so let’s move on.
Let’s Finally Make Our Request
Below is code snippet of the JavaScript code used for this project
const divForImg = document.getElementById("img-box");//enter your api key where it says YOUR_ACCESS_KEYconst requestOne = "https://api.unsplash.com/search/photos?page=1&query=&client_id=YOUR_ACCESS_KEY";const requestTwo = "https://api.unsplash.com/search/photos?page=2&query=expensive-cars&client_id=YOUR_ACCESS_KEY"function makeRequestToUnsplash(requestUrl){ fetch(requestUrl)
.then( res => res.json())
.then((data) => { //we are actually using the returned data from the API here
// data.results contains an array of objects so we can use an array method here to iterate data.results.forEach( (imageObj) =>{
createImage(imageObj);
}); });
}// the function createImage() below is a helper function used to generate an image tag for use in our web pagefunction createImage(imageObj){ const imageDiv = document.createElement("div");
const image = document.createElement("img"); // styling for the elements image.src = imageObj.urls.regular;
image.alt = imageObj.alt_description;
image.style.margin = "20px";
image.style.width = "600px";
image.style.height = "500px";
image.style.border = "double 4px black"
imageDiv.append(image);
divForImg.append(imageDiv);}//each call to makeRequestToUnsplash() returns data with 10 images in it
//so I make two calls to it to get 20 images to populate the page with imagesmakeRequestToUnsplash(requestOne);
makeRequestToUnsplash(requestTwo);
Now let me explain what the code in this snippet is doing.
In the first line we got access to the following tag in our html code: <div id = "img-box"></div>
. We need this because this is where our images will be added in the page. In the next two lines we create 2 variables to store two different api calls to the unsplash API.
Let’s take a closer look at the string stored inside our requestOne
variable. Inside it, we have a string of the url of a request to be used inside the fetch method. The main url used in all requests to the Unsplash API is https://api.unsplash.com
and it is used in every API call that we make to Unsplash. Everything we put after the main url is called an API endpoint, and each endpoint will allow us to access a different piece of Unsplash’s database.
The endpoint that we are using in requestOne
will allow us to search unsplash’s database for a specific key word and return 10 pictures associated with that key word. The key word that we are using in our search is “expensive cars”. The second request we make has the same keyword in its search but gets 10 different pictures than what the first request returns.
It is important to note here than when we have access to our data from the second .then()
, we should make sure to log the result of that data to the console to see what kind of data structure we are working with. This is a great practice to have as you should always be checking to see what form your data comes in.
Inside our second .then()
method we call a function that we made later in our code that takes the data from unsplash and uses it to create an image tag <img>
with an image source, alt text and some basic styling. The reason why called our function here is because this is the only point in which we can use the data that we requested.
Adding this code snippet will make our page look like this:
Now it’s Your Turn
If you got this far and followed along, you have successfully made your own fetch request to a real API….yay
Now that you’ve done that it’s your turn to make the project your own. One of the most important things you can do to get the most out of project based learning is to add something of your own to the project.
So I challenge you to add something extra to the project to make it your own. If you don’t know what to add here are some suggestions:
- Make some request to some of Unsplash’s other API endpoints
- Take this project and make it into a full website
- Add some additonal JavaScript feature that you would like to see on a page like this
Additional Resources
As Promised here are some more resources to help you understand this topic
More about Promises:
javascript.info explanation of promises
More about fetch:
A Great Resource on How to Hide API Keys:
If you enjoyed this post and would like to see other small tutorials like this one, please share this post and let me know what you think of it in the comment section.
Feel free to reach out to me on Twitter as well if you have any questions about this post, I would love to hear from you.