#AD Top Online Web Development & Programming Courses | Udemy

Fetch & display API data using JavaScript

Last modified March 11th 2022 | #js | GitHub Source Code [GitHub]

In this tutorial you’ll learn how to fetch data from a remote API and output that data into a HTML page. Learning to work with API’s is a handy skill to have as it allow’s you to build applications from data others have created.

The API we’ll be using is TheCocktailDB a free API with over 600 drink recipes that doesn’t require an account to get started. If cocktails aren’t your thing there’s also TheSportsDB, TheAudioDB, and TheMealDB, all of which are also free and publicly available.

We’ll be building a page that fetches a random cocktail like the following:

Let’s get started by creating a HTML file with the following markup:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Random Cocktail Recipe</title> <link href="style.css" rel="stylesheet" /> </head> <body> <div id="cocktail"></div> <div id="overlay"></div> <script src="script.js"></script> </body> </html>
Code language: HTML, XML (xml)

Next in the script.js file we’ll make our request using the Fetch API. Currently supported in all browsers excluding IE and Opera Mini, 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 => { console.log(data); displayCocktail(data) }) .catch((error) => console.error("FETCH ERROR:", error));
Code language: JavaScript (javascript)

If the request was successful you’ll be able to view the data in the console:

Console API Data

We can now pass this data to a function that will render it into the HTML. Create a displayCocktail() function in script.js. We’ll then declare variables for the data and the <div> used to output the data:

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

Now let’s output 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); ...
Code language: JavaScript (javascript)

Next let’s get the image and also add it to the cocktail <div>. We’ll also use this image as the background for the <body>:

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

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 unordered list:

... 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); } ...
Code language: JavaScript (javascript)

That concludes the JavaScript.

All that’s left to do is add the following CSS to the style.css file:

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; }
Code language: CSS (css)

In this tutorial you learnt how to build a webpage that displays a random cocktail recipe from an API. If you would like to learn more about the Fetch API check out the MDN web docs.

Related Posts

#AD Shop Web Developer T-Shirts