Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to Use the JavaScript Fetch API to Get Data

Fetching data from a server or an API (Application Programming Interface) is a common task in web development. JavaScript provides a simple and elegant way to fetch data from a remote source using the Fetch API. In this tutorial, we'll learn about the Fetch API and how you can use it to get data from a server.

Please note: This tutorial is intended for beginners who are learning programming, so we'll try to avoid jargon as much as possible. If we do use any technical terms, we'll make sure to explain them.

What is Fetch API?

The Fetch API is a modern, powerful and flexible way to make HTTP requests in JavaScript. It is built into the language, which means you don't need to include any external libraries to use it. The Fetch API provides a global fetch() method that can be used to request data from an API or a server. It returns a Promise that resolves to the Response object representing the response to the request.

Before we dive into the Fetch API, let's quickly understand what a Promise is.

Promises

A Promise is a JavaScript object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. A Promise is in one of three states:

  1. Pending: The initial state; neither fulfilled nor rejected.
  2. Fulfilled: The operation completed successfully, and the resulting value is available.
  3. Rejected: The operation failed, and an error reason is available.

A Promise is said to be "settled" if it is either fulfilled or rejected. You can attach callbacks to a Promise using the .then() and .catch() methods. The .then() method is called when the Promise is fulfilled, while the .catch() method is called when the Promise is rejected.

Now that we have a basic understanding of Promises, let's dive into using the Fetch API.

Using the Fetch API

Using the Fetch API is quite simple. You just need to call the global fetch() method and provide the URL of the resource you want to fetch. The fetch() method returns a Promise that resolves to a Response object. Let's see an example:

fetch('https://api.example.com/data')
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.error('Error fetching data:', error);
  });

In the example above, we are fetching data from https://api.example.com/data. The fetch() method returns a Promise, and we are using the .then() method to handle the successful response and the .catch() method to handle any errors.

The Response object that we receive in the .then() method contains several properties and methods that can be used to extract the data from the response. Some of the most commonly used properties and methods are:

  • response.ok: A boolean value that indicates whether the request was successful (status code in the range 200-299) or not.
  • response.status: The status code of the response (e.g., 200, 404, 500, etc.).
  • response.statusText: A status message corresponding to the status code (e.g., "OK", "Not Found", "Internal Server Error", etc.).
  • response.headers: An object representing the headers of the response.
  • response.json(): A method that returns a Promise that resolves to the JSON object resulting from parsing the response's body text as JSON.
  • response.text(): A method that returns a Promise that resolves to the response's body text as a string.

In most cases, you'll want to extract the JSON data from the response. Let's modify our previous example to parse the JSON data:

fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error('Error fetching data:', error);
  });

In this example, we first check if the response.ok property is true. If it is not, we throw an error that will be caught by the .catch() method. Otherwise, we call the response.json() method, which returns a Promise that resolves to the JSON data. We then use another .then() method to handle the JSON data.

You can also fetch data in other formats, like text or binary data (e.g., images, audio files, etc.). To fetch data as text, you can use the response.text() method, like this:

fetch('https://api.example.com/data.txt')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.text();
  })
  .then(text => {
    console.log(text);
  })
  .catch(error => {
    console.error('Error fetching data:', error);
  });

Using Fetch with Async/Await

Another way to handle asynchronous operations in JavaScript is by using the async/await syntax. This allows you to write asynchronous code that looks and behaves like synchronous code, which makes it easier to read and understand.

To use async/await with the Fetch API, you need to follow these steps:

  1. Declare an async function. This tells JavaScript that the function will contain asynchronous code.
  2. Inside the async function, use the await keyword before calling the fetch() method. This tells JavaScript to wait for the Promise to resolve before continuing with the rest of the code.
  3. Use try/catch blocks to handle errors.

Here's an example of how to use the Fetch API with async/await:

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}

fetchData();

In this example, we've declared an async function called fetchData(). Inside this function, we use the await keyword before calling the fetch() method and the response.json() method. This makes the code easier to read and understand.

Conclusion

In this tutorial, we learned about the JavaScript Fetch API and how to use it to fetch data from an API or a server. We also learned about Promises and how to handle asynchronous operations using the .then() and .catch() methods, as well as the async/await syntax.

The Fetch API is a powerful and flexible way to make HTTP requests in JavaScript, and it is an essential tool