How to Use the Fetch API in JavaScript to Request Data

One of the most common needs in modern web development is fetching data from a server or an external API. We used to rely on XMLHttpRequest, which was fairly complex, but now JavaS...

How to Use the Fetch API in JavaScript to Request Data

One of the most common needs in modern web development is fetching data from a server or an external API. We used to rely on XMLHttpRequest, which was fairly complex, but now JavaScript provides the Fetch API — a cleaner, modern, Promise-based way to make HTTP requests. This article covers how to use the Fetch API from the very basics to real-world usage.

What Is the Fetch API?

The Fetch API is a native browser interface that lets us send and receive data over the network. There is no need to install an extra library like Axios — just use the fetch() function that is already available in all modern browsers.

Basic Fetch Usage (GET Request)

Here is the simplest example of fetching data from a public API:

// GET request using the Fetch API
fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => {
    // Check whether the response was successful
    if (!response.ok) {
      throw new Error('Network response was not ok: ' + response.status);
    }
    return response.json(); // Parse JSON from the response
  })
  .then(data => {
    console.log('Data fetched successfully:', data);
    console.log('Title:', data.title);
  })
  .catch(error => {
    console.error('An error occurred:', error);
  });

The fetch() function returns a Promise. We use .then() to handle the response and .catch() to catch errors. Note that we need to call response.json() to turn the response body into a JavaScript object we can use.

Using Async/Await with Fetch

A more modern and readable approach is to use async/await:

async function fetchData() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts');

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    const posts = await response.json();
    console.log(`Successfully fetched ${posts.length} posts`);

    // Display the first 3 posts
    posts.slice(0, 3).forEach(post => {
      console.log(`- ${post.title}`);
    });

  } catch (error) {
    console.error('Failed to fetch data:', error.message);
  }
}

fetchData();

POST Request with Fetch

Not just GET — we can also send data to the server using the POST method. We need to add a second argument to the fetch() function:

async function sendData() {
  const newData = {
    title: 'Learning the Fetch API',
    body: 'The Fetch API is very easy to use.',
    userId: 1
  };

  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(newData) // Turn the object into a JSON string
    });

    if (!response.ok) {
      throw new Error('Failed to send data');
    }

    const result = await response.json();
    console.log('Data sent successfully! New ID:', result.id);

  } catch (error) {
    console.error('Error:', error.message);
  }
}

sendData();

Sending a Request with Custom Headers (Authorization)

When working with an API that requires authentication, we need to add an Authorization header:

async function fetchPrivateData(token) {
  const response = await fetch('https://api.example.com/my-data', {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  });

  if (response.status === 401) {
    throw new Error('Token is invalid or has expired');
  }

  return await response.json();
}

Displaying Data on an HTML Page

Here is a real-world example of displaying API data on a web page:

async function displayPosts() {
  const container = document.getElementById('post-container');
  container.innerHTML = '<p>Loading data...</p>';

  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts?_limit=5');
    const posts = await response.json();

    container.innerHTML = posts.map(post => `
      <div class="card">
        <h3>${post.title}</h3>
        <p>${post.body}</p>
      </div>
    `).join('');

  } catch (error) {
    container.innerHTML = `<p style="color:red">Error: ${error.message}</p>`;
  }
}

document.addEventListener('DOMContentLoaded', displayPosts);

The Difference Between response.json(), response.text(), and response.blob()

  • response.json() — used for data in JSON format (the most common).
  • response.text() — used for plain text or HTML data.
  • response.blob() — used for binary data such as images or files.

Conclusion

The Fetch API is the modern, standard way to make HTTP requests in JavaScript without an extra library. By understanding how to make GET and POST requests, handle errors, and use async/await, you are ready to integrate APIs into your web projects. The best practice is to try it directly with a public API like JSONPlaceholder to get comfortable before using a real API.

fetch api javascript request data javascript fetch get post javascript ajax modern cara pakai fetch api
Share this article
Back to Blog

Related Articles

Discover more relevant articles

🚀 Partner Recommendation

Need Premium Source Code & Business Apps?

Access Laravel applications, POS systems, School Management, Clinic Software, ERP solutions, and ready-to-use premium source code at GudangCode.

GudangCode
  • ✔ Premium Source Code
  • ✔ Ready-to-Use Systems
  • ✔ Lifetime Updates
  • ✔ Lifetime Membership
  • ✔ Daily App Updates
Join Membership →