Choose Language

Analyze ⏱ 30 min

Fetch API Introduction – Beginners Guide to JavaScript Fetch API

What You Will Learn

  • How to use the Fetch API to make asynchronous requests to a server
  • How to handle responses and errors using promises and the .then() method
  • How to send POST requests using the Fetch API

Key Concepts

The Fetch API is a modern JavaScript feature for making asynchronous requests to a server. It returns a promise, which is a placeholder for the response that will be received. The .then() method is used to handle the response, and the .catch() method is used to handle any errors that may occur. The Fetch API can be used to send GET, POST, PUT, and DELETE requests, among others.

Code Examples

fetch('sample.txt')
  .then(res => res.text())
  .then(data => console.log(data));
// Fetches the contents of a text file and logs it to the console
fetch('users.json')
  .then(res => res.json())
  .then(data => {
    let output = '<h2>Users</h2>';
    data.forEach(user => {
      output += `<ul>
        <li>ID: ${user.id}</li>
        <li>Name: ${user.name}</li>
        <li>Email: ${user.email}</li>
      </ul>`;
    });
    document.getElementById('output').innerHTML = output;
  });
// Fetches a JSON file, parses it, and displays the data in the browser
fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title: 'Test Title',
    body: 'Test Body'
  })
})
.then(res => res.json())
.then(data => console.log(data));
// Sends a POST request to a server with a JSON payload

Lesson Summary

In this lesson, we learned about the Fetch API, a modern JavaScript feature for making asynchronous requests to a server. We saw how to use the fetch() function to send GET requests and retrieve data from a server, and how to handle the response using the .then() method. We also learned how to send POST requests using the Fetch API, and how to handle errors using the .catch() method. The lesson included examples of fetching text files, JSON files, and making POST requests to a server. The instructor also emphasized the importance of learning older technologies, such as XHR and AJAX, in addition to newer ones like the Fetch API.

Practice Exercise

Create a simple web page that uses the Fetch API to retrieve a list of users from a JSON file and display them in a list. Use the .then() method to handle the response and display the data in the browser.

What Is Next

In the next lesson, we will learn about more advanced topics in the Fetch API, such as handling errors and using async/await syntax. We will also explore how to use the Fetch API with other JavaScript features, such as promises and async/await.