Swift  

How to Fetch API Data in JavaScript

Introduction

Fetching data from APIs is one of the most common tasks in modern web development. Whether you're building a simple website or a full-scale application, APIs allow you to retrieve dynamic data such as user information, products, or posts from a server.

In simple terms, an API (Application Programming Interface) acts like a bridge between your frontend (browser) and backend (server).

What is Fetch API?

The Fetch API is a modern JavaScript interface used to make HTTP requests. It is built into the browser and provides a cleaner, promise-based alternative to older methods like XMLHttpRequest.

Basic Example Using Fetch

Below is a simple example of how to fetch data from a public API:

fetch("https://jsonplaceholder.typicode.com/posts")
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error(error));

How It Works

  • fetch() sends a request to the given URL.

  • The response is returned as a Promise.

  • response.json() converts the response into usable JSON data.

  • .catch() handles any errors during the request.

Using Async/Await (Recommended Approach)

Async/Await makes your code cleaner and easier to read, especially for beginners.

async function getData() {
  try {
    const res = await fetch("https://jsonplaceholder.typicode.com/posts");
    const data = await res.json();
    console.log(data);
  } catch (err) {
    console.error(err);
  }
}

getData();

Real-World Example

Imagine you are building a blog page. Instead of hardcoding posts, you can fetch them from an API and display them dynamically.

async function loadPosts() {
  const response = await fetch("https://jsonplaceholder.typicode.com/posts");
  const posts = await response.json();

  const container = document.getElementById("posts");

  posts.slice(0, 5).forEach(post => {
    const div = document.createElement("div");
    div.innerHTML = `<h3>${post.title}</h3><p>${post.body}</p>`;
    container.appendChild(div);
  });
}

loadPosts();

Handling Errors Properly

Always check if the response is successful before parsing JSON:

async function getDataSafe() {
  try {
    const res = await fetch("https://jsonplaceholder.typicode.com/posts");

    if (!res.ok) {
      throw new Error("Network response was not ok");
    }

    const data = await res.json();
    console.log(data);
  } catch (error) {
    console.error("Error fetching data:", error);
  }
}

Advantages of Using Fetch API

  • Built into modern browsers

  • Promise-based and easy to use

  • Cleaner syntax with async/await

  • Supports various HTTP methods (GET, POST, PUT, DELETE)

Disadvantages

  • Does not reject on HTTP errors by default

  • Requires manual error handling

  • Older browsers need polyfills

Conclusion

Fetching data using JavaScript is a fundamental skill for any web developer. By using the Fetch API and async/await, you can write clean, readable, and efficient code to interact with APIs.

Start practicing with public APIs to get comfortable with real-world scenarios.