A Vanilla javascript project using dog api (Part-2)

This blog is a part of a blog series to make a vanilla javascript project using the Dog Api to show beginners how to use an API .Please check the first part if you haven’t already.

Overview

So, you’ve learned how to get a random image from the API and show it in html . Now, let’s take things further and get a list of dog breeds from the api and show it in a <ul> tag in html .

We will be using this list of dog breeds to fetch the corresponding images in the next blog .

Pre-requisites

  • Basic HTML
  • Basic CSS
  • Basic understanding of Javascript variables and functions
  • Basic understanding of DOM (document object)
  • Fetch Api (Javascript)
  • Promises (Javascript)

Let’s Begin

If you check the documentation of the dog api then you will notice there’s a section for the List all breeds . You can see that the API (url) to get the list of all breeds is https://dog.ceo/api/breeds/list/all . If you click this url you will get something like this in the browser:

{
    "message": {
        "affenpinscher": [],
        "african": [],
        "airedale": [],
        "akita": [],
        "appenzeller": [],
        "australian": [
            "shepherd"
        ],
        "basenji": [],
        "beagle": []
    },
    "status": "success"
}

As you can see there are two fields in the response : message and status. We’re interested in the message field as it contains an object with all the breed names and their respective sub-breeds.

Let’s write some code

HTML

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

  <link rel="stylesheet" href="style.css">

</head>
<body>

  <!-- we will add breed names as <li> tag from js-->
  <ul id="ul_breeds">
  </ul>
   
  <script src="main.js"></script>
  
</body>
</html>

We just created a very simple page with a <ul> tag and gave it an id

CSS

#ul_breeds{
  list-style-type: none;
  padding: 0px;
  margin: 0px;
  width: 200px;
  background-color: #f5f7f9;
}
#ul_breeds li{
  padding: 10px;
}
#ul_breeds li:hover{
  padding: 10px;
  background-color: #d5d7d9;
}

Here we gave some very basic styling to our list and list items .

Javascript

//we saved the <ul> element in a global variable so we can use it anywhere in the code
const ul_breeds = document.getElementById("ul_breeds");

// a function which is responsible to fetch data from server and pass it to parseJsonResponse() function
function getDogBreeds(){
  const allBreedsApiUrl = "https://dog.ceo/api/breeds/list/all";

  // we are using fetch api to make rest api calls. you can use axios .
  // we are also using promises here. 
  fetch(allBreedsApiUrl)
    .then(function(response){
      // we get raw response. need to first convert it into json format so we can use the data easily
      return response.json();
    })
    .then(function(json){
      // now we got the json . we can use this to update any data in html 
      console.log(json);

      //we don't want to write everything in callbacks so we gave the responsibility of showing data in html to a seperate function
      parseJsonResponse(json);
    })
    .catch(function(error){
      // if any error occurs like no internet connection then this callback will be called
      console.log(error);
      
    });
}

//a seperate function which is responsible to show the json data in html
function parseJsonResponse(json){

  //get the object containing all the breeds data
  var allBreedsData = json.message;

  // we need only breed names from this object which are actually all the keys of this object
  // so we can use Object.keys(object) function to get a list of all the keys in this object
  var breedsList = Object.keys(allBreedsData);

  //reset all the current items in the list if any
  ul_breeds.innerHTML="";

  //now we can iterate thriugh this list and show all the breed names in a list in html
  // we are using forEach loop. you can also use for loop
  breedsList.forEach(function(breed){
    //we use template literals to generate the html for our single list item
    var listItemHtml = `<li> ${breed} </li>`;
    // += is used to keep adding more list items in the list without removing the already available items in the list
    ul_breeds.innerHTML+=  listItemHtml;
  })
}

//call the getDogBreeds function whenever page loads
getDogBreeds();
Explanation of what we did above

We only two functions here : one to fetch data from server and the other to show this data in the html

We generally divide the responsibilities between several functions to make code clean and easy to read.

If you have followed previous blog, then you already know what getDogBreeds() function do .

Let’s focus on the parseJsonResponse() function:

It takes json as an argument so we will pass json when calling it from the fetch api callback. This json is like this :

{
    "message": {
        "affenpinscher": [],
        "african": [],
        "airedale": [],
        "akita": [],
        "appenzeller": [],
        "australian": [
            "shepherd"
        ],
        "basenji": [],
        "beagle": []
    },
    "status": "success"
}

Now we will convert this in a list of breeds in steps. First, we get the message object with

var allBreedsData = json.message;

Now to convert this message object into an array we will take all the keys of this object and save it in an array. As you can see, we already have a built in js function which does this for us : Object.keys()

  var breedsList = Object.keys(allBreedsData);

Now we finally got our list of breeds. It looks something like this

["affenpinscher","african","airedale","akita","appenzeller","australian","basenji","beagle"]

then we reset the current ul list just to be sure the ul is empty. otherwise, everytime we call this function it will keep adding the breeds to same list instead of refreshing it.

ul_breeds.innerHTML="";

innerHTML means the data that is between opening and closing tag. Check this if you’re still confused about innerHTML.

finally, we iterated over the list and added each breed to ul one by one.

breedsList.forEach(function(breed){
    //we use template literals to generate the html for our single list item
    var listItemHtml = `<li> ${breed} </li>`;
    // += is used to keep adding more list items in the list without removing the already available items in the list
    ul_breeds.innerHTML+=  listItemHtml;
  })

If you don’t know about the template literals, this is a good resource you can read.

Output

All the code is available on github

You did it ! 🎉 🎊

What’s Next

In the next part, we will show images for each breed in a grid when the breed name is clicked.

If you have any questions or suggestions, please feel free to write it in the comments section below.

Leave a Comment

Your email address will not be published. Required fields are marked *