[MB]

Fetch & display data from a remote API using JavaScript

Last modified on August 30th 2020 GitHub [Source] CodePen [Demo]

In this article you’ll learn how to fetch data from an API and output that data into HTML.

This is a handy skill to learn as it will allow you to build applications from data others have created.

Here are some free APIs you can experiment with that don’t require an account:

I’ll be using TheCocktailDB in this article to create the following:

Let’s get the project started by creating a HTML file with this code.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Fetch & display data from a remote API using JavaScript</title> <link rel="stylesheet" href="style.css" /> </head> <body> <div id="cocktail"></div> <div id="overlay"></div> <script src="script.js"></script> </body> </html>

Next in the script.js file we’ll make our fetch() request.

The Fetch API provides a simple interface for fetching HTTP resources.

fetch("https://www.thecocktaildb.com/api/json/v1/1/random.php") .then((response) => { if (response.ok) { return response.json(); } else { throw new Error("NETWORK RESPONSE ERROR"); } }) .then(data => displayCocktail(data)) .catch((error) => console.error("FETCH ERROR:", error));

If the fetch() was successful you should be able to view the data in the browser console.

Console API Data

We can now pass this data to a function that will display it on our page.

First create a displayCocktail() function in script.js.

Then assign variables for the data and <div> in which we’ll output the data.

function displayCocktail(data) { const cocktail = data.drinks[0]; const cocktailDiv = document.getElementById("cocktail"); }

Now we’re ready to start outputting the data into our HTML starting with the cocktail name.

... const cocktailName = cocktail.strDrink; const heading = document.createElement("h1"); heading.innerHTML = cocktailName; cocktailDiv.appendChild(heading); ...

Next let’s get the image URL and add it to our cocktail <div>.

We’ll also set it as the background image for the <body>– you’ll see why in the finished project.

... const cocktailImg = document.createElement("img"); cocktailImg.src = cocktail.strDrinkThumb; cocktailDiv.appendChild(cocktailImg); document.body.style.backgroundImage = "url('" + cocktail.strDrinkThumb + "')"; ...

The ingredients are more difficult to output as they’re not stored in an array we can easily loop through.

To get around this we’ll create an object and only add the ingredients that don’t have a null value.

We can then loop through these ingredients and output them into the ingredients <ul>.

... const cocktailIngredients = document.createElement("ul"); cocktailDiv.appendChild(cocktailIngredients); const getIngredients = Object.keys(cocktail) .filter(function (ingredient) { return ingredient.indexOf("strIngredient") == 0; }) .reduce(function (ingredients, ingredient) { if (cocktail[ingredient] != null) { ingredients[ingredient] = cocktail[ingredient]; } return ingredients; }, {}); for (let key in getIngredients) { let value = getIngredients[key]; listItem = document.createElement("li"); listItem.innerHTML = value; cocktailIngredients.appendChild(listItem); } ...

That concludes the JavaScript.

All that’s left to do is add the following CSS to style.css so it all looks good.

html { height: 100%; } body { display: flex; justify-content: center; align-items: center; height: 100%; background-size: cover; font-family: sans-serif; } #overlay { background: rgba(147, 135, 242, 0.9); position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: -1; } #cocktail { max-width: 350px; text-align: center; padding: 30px 30px 12px 30px; color: #fff; background-color: #7766d7; border: 4px solid #9387f2; border-radius: 5px; } #cocktail h1 { margin: 0 0 15px 0; text-transform: uppercase; } #cocktail img { max-width: 300px; border: 6px solid #fff; border-radius: 150px; } #cocktail ul { list-style: none; margin: 0; padding: 0; } #cocktail li { padding: 15px 0; font-size: 18px; } #cocktail li:not(:last-of-type) { border-bottom: 1px solid #fff; }

fetch() is currently supported in all browsers excluding Internet Expoler and Opera Mini.