JavaScript Fetch API

Introduction

While creating a web application, sometimes we need to work with external data. In order to get that data, we make use of API’s. To learn more about web API’s, refer to this.

 

The Fetch API is an interface that allows web browsers to send HTTP requests to servers. Anyone who has used XMLHttpRequest will recognize it, but the new API has a more prosperous and flexible feature set. 

 

The Fetch API is also a lot simpler and cleaner. It makes use of Promise to provide more flexible options for making server requests from web browsers.

 

In this article, we’ll learn about the Fetch API, it’s usage and importance. So, let’s get started!

The 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.

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:

let fetchResponse = fetch(weburl);

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

Syntax:

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

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


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();

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

Output:

400

Not Found

 

  • 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.

Frequently asked questions

1). What is the fetch API?

Ans: The Fetch API is an interface that allows web browsers to send HTTP requests to servers. 


2). What is a Promise in the fetch API?

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

 

3). What is the use of the fetch() function?

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

 

Key Takeaways

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().

 

In this article, we learnt the basics of fetch API.

 

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


Happy Learning!

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think