Table of contents
1.
Introduction
2.
What is Fetch API?
3.
Interfaces used in Fetch API
4.
JavaScript fetch() Method Examples
5.
Sending a request using Fetch API
5.1.
Syntax
5.2.
Syntax
6.
Reading a response using Fetch API
7.
Handling response in Fetch API
8.
JavaScript fetch() Method Use Cases
9.
Frequently asked questions
9.1.
What is the fetch JSON method in JavaScript?
9.2.
What is a Promise in the fetch API?
9.3.
What is the use of the fetch() function?
10.
Conclusion
Last Updated: Oct 23, 2024
Medium

JavaScript Fetch API

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

While creating a web application, it's very necessary to interact with external data, and APIs play a crucial role in doing this. The Fetch API is a modern interface available in web browsers, which enhances our ability to send HTTP requests to servers. It is designed as a more powerful and flexible successor to XMLHttpRequest, the Fetch API streamlines the process with a simpler, cleaner syntax. With the help of Promises, it offers more flexible and robust options for making server requests, which allows for better handling of asynchronous operations. In this article, we'll talk about the Fetch API, understand its usage, and its importance in web development. 

JavaScript Fetch API

What is Fetch API?

Necessity fueled the development of Fetch API. But, before we get too far into the Fetch API, let's take a quick look at its development.

 

  • Before the notion of AJAX (Asynchronous JavaScript and XML) was introduced, browsers used to make a request for a full web page to the server even for updating a small portion of the web page. And once the request was received by the server, it used to generate and return a page to the browser as a response. It means that even with a minor update, the page was completely loaded. Wasn't that bad? 

 

  • When AJAX first appeared on the internet, it revolutionised the way pages were updated. AJAX enabled web applications to transmit and get data from a server asynchronously (in the background) without interfering with the existing page's appearance and behaviour.

 

  • W3C released a definition for the XMLHttpRequest object in 2006. The XMLHttpRequest object is used to asynchronously retrieve data from a server.

 

  • XMLHttpRequest was originally used to fetch XML data over HTTP. However, it may now be used with protocols other than HTTP and can retrieve data in formats other than XML, such as JSON, HTML, or plain text.

 

Note: The original concept for the XMLHttpRequest object was developed by the Outlook Web Access developers (by Microsoft).
 

We've been using XMLHttpRequest for several years to request data other than XML, and this is where beginners get confused when learning how to create an asynchronous request in Javascript.

 

Isn't there a more streamlined and straightforward API for making an asynchronous request? 

Yes, there is, and in order to do so, we must return to the present.

Fetch is a new native JavaScript API that is now supported by the majority of browsers. Fetch allows you to make network requests in the same way as XMLHttpRequest does. It's a step up from the XMLHttpRequest API. The primary distinction between Fetch and XMLHttpRequest is that the Fetch API use Promises, which avoids callback hell.

Interfaces used in Fetch API

The Fetch API makes use of the following interfaces:
 

  1. fetch(): Used to fetch a resource.
  2. Headers: It represents response or request headers, allowing us to make a query and take different actions depending on the results.
  3. Request: It represents a resource request.
  4. Response: It represents the response to a request.

JavaScript fetch() Method Examples

The JavaScript `fetch()` method is a powerful and versatile tool used in web development to make network requests. This method is part of the Fetch API, which provides a more modern and efficient way to fetch resources over the network compared to older methods like `XMLHttpRequest`. The `fetch()` function returns a Promise, which resolves to the `Response` object representing the response to the request. This allows for handling both success and failure scenarios cleanly and functionally through promise chaining.

Let's look at some examples of how to use the `fetch()` method in different scenarios:

  1. Basic GET Request:
fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(error => console.error('Error:', error));

This example shows a simple GET request to retrieve data from a specified URL. The response is expected to be in JSON format, so `.json()` is used to convert the response stream to a JavaScript object.

 

2. POST Request with JSON Body:


  fetch('https://api.example.com/data', {
      method: 'POST',
      headers: {
          'Content-Type': 'application/json'
      },
      body: JSON.stringify({
          name: 'John Doe',
          email: 'john@example.com'
      })
  })
  .then(response => response.json())
  .then(data => console.log('Success:', data))
  .catch(error => console.error('Error:', error));

This example sends a POST request with a JSON body to the server. It includes setting the HTTP method to POST, specifying headers, and converting a JavaScript object to a JSON string for the body.

 

3. Handling HTTP Errors:

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

Here, the fetch operation includes error handling that checks if the response is successful (i.e., `response.ok` is true). If the response is not successful, it throws an error that is caught by the `.catch()` method.

 

4. Sending Credentials with a Request:

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

This example shows how to include credentials like cookies with the request by setting the `credentials` option to 'include.' This is useful for making requests to endpoints that require session authenticity.

Sending a request using Fetch API

The fetch() method is a global scope method that tells web browsers to send a request to a URL. The URL of the resource is the only parameter required by fetch().

Syntax

The fetch() method returns a Promise, which you may handle with the then() and catch() methods.
 

let fetchResponse = fetch(weburl);

Syntax

The resource will be available once the request has been completed. The Promise will become a Response object at this point.

fetch(url)
   .then(response => {
       // handle response
   })
   .catch(error => {
       // handle error
   });


The fetched resource is wrapped in the Response object, which is an API wrapper for it. The Response object provides several attributes and methods that can be used to examine the response.

Reading a response using Fetch API

We can use the text() function if the contents of the response are in raw text format. 


The text() method produces a Promise that resolves with the fetched resource's entire contents.

fetch('/readme.txt')
   .then(response => response.text())
   .then(data => console.log(data));

 

In fact, we'll frequently utilize async/await with the retrieve() method, as shown below:

async function fetchText() {
   let response = await fetch('/readme.txt');
   let data = await response.text();
   console.log(data);
}

 

Aside from the text() function, the Response object offers various methods to handle different types of data, such as json(), blob(), formData(), and arrayBuffer().

Handling response in Fetch API

The status and statusText attributes of the Response object provide the status code and text. 

 

  • The status code for a successful request is 200, and the status text is OK.
async function fetchText() {
   let response = await fetch('/readme.txt');


   console.log(response.status); // 200
   console.log(response.statusText); // OK


   if (response.status === 200) {
       let data = await response.text();
       // handle data
   }
}


fetchText();
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

200
OK

 

The response code 404 is sent if the requested resource does not exist.

let response = await fetch('/non-existence.txt');

console.log(response.status); // 400
console.log(response.statusText); // Not Found
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

400
Not Found

 

Try this code with online javascript compiler for better understanding.
 

  • The response code 500 will be returned if the requested URL returns a server error.
     
  • The status of the Response object is set to 200 if the requesting URL is redirected to a new one with the response 300-309. The rerouted property is also set to true.

 

When a true failure happens, such as a web browser timeout, a network connection loss, or a CORS(Cross-origin resource sharing) violation, get() returns a promise that is rejected.

JavaScript fetch() Method Use Cases

The fetch() method in JavaScript is highly versatile and can be used in many scenarios in web development like:

  • Dynamic Data Loading: The fetch() method is ideal for dynamically loading data without reloading the web page. It allows developers to retrieve data from a server and update the content of a webpage in real-time, enhancing user experience.
  • Single-page applications (SPAs): In SPAs, fetch() plays a crucial role in interacting with APIs to obtain data that dictates the display on the client side, thereby supporting the seamless user experience that SPAs are known for.
  • Form Submission: Instead of traditional form submissions that require a page reload, fetch() can be used to submit form data asynchronously. This process helps send form data to the server and handle the response without disrupting the user's interaction with the page.
  • File Upload: The fetch() method can also handle file uploads. Developers can use it to send files to a server asynchronously which is useful in creating responsive, user-friendly file upload features.
  • Polling: For applications that require regular updates from the server, such as live sports scores or stock market feeds, fetch() can be used to poll the server at regular intervals, ensuring that the displayed data is kept current without full page refreshes.
  • Interacting with APIs: Whether it’s third-party APIs for data like maps and weather or internal APIs for server data, fetch() is the tool of choice for making HTTP requests, processing the responses, and integrating the data into web applications.
  • Progressive Web Apps (PWAs): For PWAs, fetch() is used extensively to handle network requests and caching strategies. This is crucial for enabling offline functionality and improving the app's performance by efficiently managing data requests and responses.

Frequently asked questions

What is the fetch JSON method in JavaScript?

The fetch JSON method in JavaScript uses the `fetch()` function to retrieve JSON data from a server, which is then processed and converted to a JavaScript object.

What is a Promise in the fetch API?

The Promise object describes the result of an asynchronous operation's ultimate completion (or failure).

What is the use of the fetch() function?

In Fetch API, the fetch() method is used to request the server to load data into the websites.

Conclusion

The Fetch API is a network-based interface for retrieving resources. It has a more robust and flexible feature set that allows web browsers to send HTTP requests to servers. Fetch API defines Request and Response objects in a generic way and has better specifications in comparison to jQuery.ajax().

 

Ready to learn more? Here's a curated list of blogs on this topic for you. Do check it out!

  1. How to build a REST API 
  2. Introduction to Web API 
  3. Introduction to Web Form API
Live masterclass