How to Fetch API Data Using JavaScript


Learn How to Connect Your Website to Real-Time Data in Just Minutes!

Fetching data from an API is one of the most powerful and essential skills in modern web development. Whether you’re building a weather app, stock tracker, or social feed — JavaScript and APIs go hand in hand.

In this beginner-friendly tutorial, you'll learn how to fetch API data using JavaScript, display it on a webpage, and handle errors the right way.


🧠 What is Fetch in JavaScript?

The fetch() method is used to make HTTP requests to servers.
It allows you to:

  • Retrieve data from an API (like JSON)

  • Handle the response

  • Show it in your app or website


🛠️ Step-by-Step: Fetching API Data

✅ Step 1: Set Up Basic HTML

html
<!-- index.html -->
<!DOCTYPE html> <html> <head> <title>Fetch API Example</title> </head> <body> <h1>User Info</h1> <div id="user"></div> <script src="script.js"></script> </body> </html>

✅ Step 2: Write the JavaScript Code

javascript
// script.js
fetch('https://jsonplaceholder.typicode.com/users/1') .then(response => { if (!response.ok) { throw new Error("Network response was not ok"); } return response.json(); }) .then(data => { const userDiv = document.getElementById("user"); userDiv.innerHTML = ` <p><strong>Name:</strong> ${data.name}</p> <p><strong>Email:</strong> ${data.email}</p> <p><strong>City:</strong> ${data.address.city}</p> `; }) .catch(error => { console.error("Error fetching data:", error); });

🧾 What’s Happening Here?

  1. fetch() sends a GET request to a free API

  2. .then() handles the response object

  3. .json() converts response into usable data

  4. The data is inserted into the DOM with innerHTML

  5. .catch() handles any errors (like 404 or network issues)


🌍 Real APIs You Can Use to Practice

API NameEndpoint ExamplePurpose
JSONPlaceholderhttps://jsonplaceholder.typicode.com/postsFake blog posts/users
OpenWeatherMaphttps://api.openweathermap.org/data/2.5/weatherWeather data
CoinGeckohttps://api.coingecko.com/api/v3/coins/bitcoinCryptocurrency prices
GitHub APIhttps://api.github.com/users/octocatGitHub user info

🛡️ Best Practices

  • ✅ Always check .ok before using response data

  • ✅ Use .catch() to handle errors smoothly

  • ✅ Never expose secret API keys in public frontend code

  • ✅ Consider using async/await for cleaner code


🚀 Bonus: Using async/await Instead

javascript
async function getUser() {
try { const response = await fetch('https://jsonplaceholder.typicode.com/users/1'); const data = await response.json(); document.getElementById("user").innerHTML = ` <p>Name: ${data.name}</p> <p>Email: ${data.email}</p> `; } catch (err) { console.error("Fetch error:", err); } } getUser();

📦 Conclusion

Now you know how to fetch API data using JavaScript like a pro! This is the foundation for:

  • Weather apps 🌦️

  • News feeds 🗞️

  • Live search engines 🔍

  • Crypto trackers 📉

The more you practice fetching data and displaying it, the better your frontend skills will become.


💬 Want to build a live weather app or a news site using API data? Comment below and I’ll create the full tutorial for you!

Post a Comment

Post a Comment (0)

Previous Post Next Post