🇯🇵 日本語 | 🇺🇸 English | 🇪🇸 Español | 🇵🇹 Português | 🇹🇭 ไทย | 🇨🇳 中文

How to Use JavaScript fetch() [Beginner Friendly]

A basic method to retrieve data from APIs using asynchronous communication

🌤 Live Demo

👇 Here's what you'll see 👇

Fetching temperature...


      <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Weather Display</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      text-align: center;
      padding: 20px;
      background-color: #f0f0f0;
    }
    #weather {
      font-size: 1.5rem;
      color: #333;
    }
  </style>
</head>
<body>

  <h1>Current Temperature in Tokyo</h1>
  <p id="weather">Fetching temperature...</p>

  <script>
    async function getWeather() {
      try {
        const res = await fetch("https://api.open-meteo.com/v1/forecast?latitude=35.6895&longitude=139.6917¤t_weather=true");
        const data = await res.json();
        const temp = data.current_weather.temperature;
        document.querySelector("#weather").textContent = `Tokyo's temperature: ${temp}℃`;
      } catch (e) {
        document.querySelector("#weather").textContent = "🌧 Failed to fetch data";
        console.error("Error:", e);
      }
    }
    getWeather();
  </script>

</body>
</html>
    

🧩 Using fetch and Handling Common Issues

The fetch() function is a modern JavaScript feature that simplifies communication with APIs. As demonstrated with the weather API, you can retrieve data asynchronously from a URL and display it on the screen with just a few lines of code.

For example, you can use const res = await fetch(...) to make the request, followed by const data = await res.json() to convert the response to JSON format. This pattern is standard for most API integrations.

🚨 Common Errors and How to Handle Them

If the URL is incorrect or there are network issues, you can catch errors using a try...catch block and display a message like “Failed to retrieve data” to improve user experience.

For real-time data like weather updates, combining fetch() with setInterval() allows you to refresh the information periodically.

Keep in mind that some APIs require an access key. In such cases, refer to the official documentation and append ?apikey=your_key to the URL as needed.