A very important aspect of working as a developer is connecting to an API to fetch data from a resource called JSON which stands for Javascript Object Notation. Some common use cases of JSON include:
Storing data
Generating data structures for user input on your app
Transferring data from server to client. It primarily a back and forth connection. client to server and server to server.
Configuring and verifying data (GET, POST, PATCH, PUT, DELETE)
In this tutorial, we are going to make a very simple web app with plain javascript that will retrieve information from an API and display it on the page, client-side.
What you need to know
Basic knowledge of HTML/CSS.
Basic knowledge of JavaScript.
Working with the DOM API.
Basic knowledge of working with JSON and JavaScript objects from the API.
What we would achieve from this tutorial
Build a working app that would display various breeds of dogs.
Show a loading spinner before fetching a new dog image from its API.
fetch data from the API.
It will look like this.
Let's get started.
Introduction
To begin we would be making use of the HTTP requests to communicate to a publicly available URL endpoint. And the HTTP method we would be using is GET which retrieves a resource. Since our objective is to create a simple web app without the installation of any framework or library boilerplate such as React, Vue etc, we would be using HTML, CSS, and JavaScript.
Setting up our working environment
We would create this web app with my editor of choice which is vs code. You can use any other IDE which you are comfortable using. Open up editor and in the new directory create index.html and put in the following code below.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Dogs API</title>
</head>
<body>
<main>
<div class="container">
<header>
<h1>Dog Viewer</h1>
<select class="breeds"></select>
</header>
</div>
<div class="img-container">
<div class="container">
<div class="spinner">
🐶
</div>
<img
src="http://placecorgi.com/260/180"
class="dog-img show"
alt="friendly and intimate - man's best friend"
/>
</div>
</div>
</main>
</body>
</html>
From the above code, our app would be focused more on JavaScript and API in connection to making it work with the DOM. To beautify with structural CSS, understanding of CSS flexbox is important as you can copy the code.
style.css
img {
max-width: 100%;
height: auto;
}
a {
text-decoration: none;
}
main {
height: 100vh;
width: 100%;
}
header {
display: flex;
justify-content: space-between;
align-items: center;
position: fixed;
width: 100%;
top: 0;
right: 0;
left: 0;
padding: 5px 40px 0;
}
main .container header h1 {
font-family: Nunito;
font-size: 1.5rem;
}
main .container header select {
font-size: 1.2rem;
padding: 5px;
font-family: Poppins;
text-transform: capitalize;
}
main .img-container {
width: 100%;
margin-top: 5%;
padding: 2em 0;
}
/* animation for the dog spinner */
main .img-container .spinner {
font-size: 50px;
animation: spin 2s linear infinite;
display: none;
}
main .img-container .dog-img {
display: none;
width: 80%;
margin: 1em auto;
}
main .img-container .show {
display: block;
}
/* rotate the dog spinner 360deg - keyframes */
@keyframes spin {
to {
-webkit-transform: rotateZ(360deg);
transform: rotateZ(360deg);
}
}
/ * media query */
@media only screen and (min-width: 320px) {
.container header {
display: flex;
flex-direction: column;
}
.container header h1 {
margin-bottom: 20px;
}
}
@media only screen and (min-width: 650px) {
.container header {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
flex-direction: row;
}
}
@media only screen and (min-width: 875px) {
.container {
max-width: 80%;
margin: 0 auto;
}
}
@media only screen and (min-width: 1600px) {
.container {
max-width: 70%;
margin: 0 auto;
}
}
Now that we have our HTML and CSS setup, it is time to set up our app.js in the directory of our project.
Connecting to the actual API
Let's talk a look at the dogs ceo API and explore what it got to offer us as developers to enable us to retrieve its data and use it on the client-side of our app.
To get started, go to the list all breeds on the website documentation. It will show us the URL of our API endpoint https://dog.ceo/api/breeds/list/all. Clicking on the link will display the object of the dog types.
app.js
const BREEDS_URL = 'https://dog.ceo/api/breeds/list/all';
const select = document.querySelector('.breeds');
fetch(BREEDS_URL)
.then(res => {
return res.json();
})
.then(data => {
const breedsObject = data.message;
const breedsArray = Object.keys(breedsObject);
for (let i = 0; i < breedsArray.length; i++) {
const option = document.createElement('option');
option.value = breedsArray[i];
option.innerText = breedsArray[i];
select.appendChild(option);
}
console.log(breedsArray);
});
select.addEventListener('change', event => {
let url = `https://dog.ceo/api/breed/${event.target.value}/images/random`;
getDoggo(url);
});
const img = document.querySelector('.dog-img');
const spinner = document.querySelector('.spinner');
const getDoggo = url => {
spinner.classList.add('show');
img.classList.remove('show');
fetch(url)
.then(res => {
return res.json();
})
.then(data => {
img.src = data.message;
});
};
img.addEventListener('load', () => {
spinner.classList.remove('show');
img.classList.add('show');
});
The first thing we did here is to declare a variable to the API endpoint URL which is a constant because we don't want it to change throughout the development.
Going back to our index.html, remember our select tag with the class of breeds. Here we would make sure we create a dropdown menu for users to select to change the current image with another.
Next thing to do is to extract the JSON body content from the response, we use the JSON() method which returns us a promise that resolves to the Response to that request with data from the endpoint.
A look at the endpoint from the list of breeds API
To make it easier working with the object, we can convert it into an array using Object.keys() to loop it starting at index 0.
Within the for loop, we can then create an option tag that would list out all the dog breeds from the API and then use the innerText and finally append it to the select tag to display results from the API.
To be able to change each image from the dropdown to display a new image, we need to add an event listener to the select tag from our index.html to individually change our option from the dropdown.
The last step of this tutorial is to create a function that when you select a name from the dropdown, it first has to load the spinner and remove the image displayed on the screen from our declaration in style.css. From here, it fetches the new image and removes the spinner and displays the new image as a block element in our web app.
Conclusion
Congratulations on going through this tutorial on using plain JavaScript to connect to an API using HTTP requests. Hopefully, you should have a better understanding and with this method, you can easily fetch and communicates with any public API to fetch its data to display on a website. We did all this without having to worry about anything like Node.js, installing a package(npm), webpack and so on.
This tutorial is just an easy step by step guide to follow and I hope to you found this useful. I am open to correction and feel free to share.
Top comments (2)
Great knowledge...
I made my own website related to dog bed using the information you delivered
Check this out on best orthopedic bed for dogs with arthritis
Great post
Also dont forget to check this out Top 10 Most Popular Dog Breeds in the World