DEV Community

Robson Muniz
Robson Muniz

Posted on • Edited on

🎬JavaScript Fetch API - Easy Example 🙌

Use fetch API to get some data from an any external API
and display it on your website: step-by-step from SCRATCH…



Source Code:

HTML

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>JavaScript Fetch API | Simple Example</title>
  <link rel="stylesheet" href="style.css">
  <script src="https://kit.fontawesome.com/fc0bcca8a3.js" crossorigin="anonymous"></script>
</head>

<body>

  <div class="results">
    <div class="result" id="cat_result">
      <p>Random Cat Placeholder</p>
    </div>
    <div class="result" id="dog_result">
      <p>Random Dog Placeholder</p>
    </div>
  </div>


  <div class="buttons">
    <button id="cat_btn">
      <i class="fas fa-cat"></i> Get Cat
    </button>
    <button id="dog_btn">
      <i class="fas fa-dog"></i> Get Dog
    </button>
  </div>


  <script src="app.js"></script>
</body>

</html>

Enter fullscreen mode Exit fullscreen mode

JavaScript

const cat_result = document.getElementById('cat_result');
const dog_result = document.getElementById('dog_result');
const cat_btn = document.getElementById('cat_btn');
const dog_btn = document.getElementById('dog_btn');

cat_btn.addEventListener('click', getRandomCat);
dog_btn.addEventListener('click', getRandomDog);

function getRandomCat() {
    fetch('https://aws.random.cat/meow').then((res) => res.json()).then((data) => {
   cat_result.innerHTML = `<img src=${data.file} alt="cat" />`;
});
}

function getRandomDog() {   fetch('https://random.dog/woof.json')
.then((res) => res.json())
.then((data) => {
 dog_result.innerHTML = `<img src=${data.url} alt="dog" />`;
    });
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)