JavaScript Fetch API - Made Easy

Before we start with the JavaScript Fetch API, let’s briefly discuss APIs in general. APIs or Application Programming Interfaces are protocols that encompass rules on how two applications should communicate with each other; for an application to get the necessary resource from another application, it first needs to send requests to access the necessary resources. 

Requests to retrieve resources were sent using the XMLHttpRequest() method. Before JSON, APIs only returned XML data. However, XMLHttpRequest() is no longer widely used. Instead, the Fetch API has grown in popularity, and it is currently one of the most commonly used functions for requesting API resources.

So what is JavaScript fetch API? Here is an entire article dedicated just for you to clearly understand the functionality of the JavaScript fetch API.

🔥 Learn JavaScript Programming - Beginner Friendly!
🔨 JavaScript Basics
👉 JavaScript Array Filter
👉 JavaScript Array Find
👉 JavaScript forEach (Arrays)
👉 JavaScript Slice (Arrays)
👉 JavaScript Spread Operator
👉 JavaScript Slice(Strings)
👉 JavaScript Includes
👉 JavaScript alert()
👉 Store User Input in a variable with JS
👉 Difference between Let and Const
👉 Sorting Numbers in JS
⚙️ JavaScript Specifics
👉 JavaScript Fetch API
👉 toLocaleDateString in JavaScript

Table of Contents

What is JavaScript Fetch API?

JavaScript Fetch API

The Fetch API is a JavaScript function that sends requests to the server and updates information on the web page without refreshing the entire page. It has a similar function as XMLHttpRequest().  

The only difference is that Fetch() has extra options to help you build particular requests and manipulate sections of the HTTP pipeline.

fetch (URL, options)

Here,

  • URL - refers to the URL from which the webpage is requesting resources.
  • Options - refers to the specific options that can be specified to bring tailored results.

Return Value: It returns a promise whether it is resolved or not. 

Async Await

There is also an alternative way to use the fetch() method which is through the Async Await function. This function can be more clearly explained through the syntax:

async function funcName(url){ const response = await fetch(url); let data = await response.json(); }
Code language: JavaScript (javascript)

Here,

  • The async allows you to define a function that handles asynchronous operations.
  • The await is used to wait for the promise to be either resolved or rejected. 

It's worth noting that the await keyword is inextricably linked to async and can only be used within an async function. The fetch() function provides a promise as a response to the request, which could indicate the request's success or failure. Speaking of promises, this might raise another question, what is a promise?

Promises is a great and essential feature that makes JavaScript programming much more efficient because it has the ability to manage numerous callbacks. A promise is a placeholder value for asynchronous requests whose value you don't know ahead of time. Whether the request is successful or unsuccessful, it sends a response.

A Promise is in one of these states:

  • pending: in its preliminary form, neither fulfilled nor rejected.
  • fulfilled: denotes that the operation was successfully finished.
  • rejected: indicates that the procedure was unsuccessful.

Promise Consumers

Promises can be consumed by registering functions using the .then and .catch methods.

.then()  

When a promise is resolved or refused, the .then() method is called. It may also be defined as a carrier that takes data from the promise and further executes it successfully.

.then(function(result){ //handle success }, function(error){ //handle error })
Code language: JavaScript (javascript)

Here, the then() function takes two parameters, where,

  • The first function is executed when the promise is fulfilled.
  • When the promise is denied, the second function is called.

.catch()

The .catch() method is invoked when the promise is not fulfilled, or an error has occurred. Here is an example:

.catch(function(error){ //handle error })
Code language: JavaScript (javascript)

Since the purpose of .catch() is only to respond when an error has occurred, it has only one function.

Using JavaScript Fetch API

Using the Request() and Response() constructors, you can make a request and get a response right away.

Request()

The Request() constructor is used to create a new Request() object. The syntax is as follows:

new Request(input)
Code language: JavaScript (javascript)

Here,

  • The input refers to the URL from which you are requesting the resource.

Response()

The Response() constructor creates a new Response object. The syntax is as follows:

new Response(body)
Code language: JavaScript (javascript)

Here,

  • The body refers to the response which is meant to be sent for a specific request.

Finally, one more constructor, which is a key in making the fullest of the Fetch API, the Headers constructor.

Headers

Unlike the XMLHttpRequest() function, the Fetch() function allows programmers to conduct a variety of procedures in order to send HTTP requests to web servers.

The Headers object is responsible for retrieving, changing, adding, and removing headers from the request's list.

Here are some of the necessary methods which are used to perform actions on requests:

  • Headers.append()

append() adds a new value to an existing header or creates a new header if one does not exist.

  • Headers.delete()

Removes one of the headers from a Headers object.

  • Headers.entries()

Returns an iterator that may be used to loop through all of the key/value pairs in this object.

  • Headers.forEach()

The forEach() runs the specified function once, for each array element.

  • Headers.get()

Within a Headers object with a provided name, it returns a String sequence of all the values of a header.

  • Headers.has()

If a Headers object contains a specific header, this method returns a boolean.

  • Headers.keys()

Returns an iterator that can loop through all of the keys in the key/value pairs in this object.

  • Headers.set()

Sets a new value for an existing header inside a Headers object or creates a new header if none exists.

  • Headers.values()

Returns an iterator that allows you to loop through all of the values in this object's key/value pairs.

Sending a Request

To send the request, the response constructor along with .then() and .catch() statements are used.

fetch('URL') .then(response => response.json()) .then(data => { console.log(data) // Prints result from `response.json()` in getRequest }) .catch(error => console.error(error))
Code language: JavaScript (javascript)

The data requested will be provided as a JavaScript object in the example above. As previously stated, the fetch() method allows us to specify how the data should be returned using the following methods:

  • clone() – This function makes a response clone.
  • redirect() – This method generates a fresh response with a different URL from the previous one.
  • text() – The promise is resolved with a string.
  • arrayBuffer() – This function returns a list of arrays.
  • JSON() – This method uses JSON to resolve the promise.
  • blob() – This one is determined by a Blob, which indicates the data will be represented as file system data.
  • formData() – This method also delivers a promise, but this time it is determined by the FormData object.

JavaScript Fetch API Example

JavaScript Fetch API

Let's look at an easy example of how Fetch API can be used in performing requests and responses.

In JavaScript

// URL of API const api_url = "https://employeedetails.free.beeceptor.com/my/api/path"; // This statement defines the async function async function getapi(url) { // Storing response const response = await fetch(url); // Storing data in form of JSON let data = await response.json(); console.log(data); if (response) { hideloader(); } show(data); } // Calling that async function getapi(api_url); // Function to hide the loader function hideloader() { document.getElementById('loading').style.display = 'none'; } // Function to define innerHTML for HTML table function show(data) { let tab = `<tr> <th>Name</th> <th>Company</th> <th>Role</th> <th>Remuneration</th> </tr>`; // Loop to access all rows for (let f of data.list) { tab += `<tr> <td>${f.name} </td> <td>${f.company}</td> <td>${f.role}</td> <td>${f.remuneration}</td> </tr>`; } // Setting innerHTML as tab variable document.getElementById("employees").innerHTML = tab; }
Code language: JavaScript (javascript)

In HTML

<!DOCTYPE html> <html lang="en"> <head> <script src="script.js"></script> <link rel="stylesheet" href="style.css" /> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <! – Here a loader is created which loads till response comes – > <div class="d-flex justify-content-center"> <div class="spinner-border" role="status" id="loading"> <span class="sr-only">Loading...</span> </div> </div> <h1>Registered Employees</h1> <! – table for showing data – > <table id="employees"></table> </body> </html>
Code language: HTML, XML (xml)

For the above coding, the output will be the employee table. If you right-click and select inspect in the browser, you will open the chrome developers tool panel. Click the console to view the requested data in JSON.

Conclusion

The fetch() function aids in requesting resources from the server or API with more options. We hope you were able to understand the gist behind using JavaScript Fetch API to perform requests and retrieve responses. 

2 thoughts on “JavaScript Fetch API - Made Easy”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share via
Copy link
Powered by Social Snap