The Task here is to show how the Fetch API can be used to get data from an API. I will be taking a fake API which will contain employee details as an example and from that API. I will show to get data by fetch() API method.
fetch() method: The fetch() method is modern and versatile and is very well supported among the modern browsers. It can send network requests to the server and load new information whenever it’s needed, without reloading the browser.
- Syntax: The fetch() method only has one mandatory argument, which is the URL of the resource you wish to fetch.
let response = fetch(api_url, [other params])
Async Await: In this example, we will be using Async Await method with fetch() method to make promises in a more concise way. Async functions are supported in all modern browsers.
- Syntax:
async function funcName(url){ const response = await fetch(url); var data = await response.json(); } - Prerequisite: Here, you will need an API for performing fetch() operation to get data from that API. You can also create an API or can take free mock APIs.
- Here the API I used is: This API contains employee details in the form of key : value pair.
https://employeedetails.free.beeceptor.com/my/api/path
Approach: First make the necessary JavaScript file, HTML file and CSS file. Then store the API URL in a variable (here api_url). Define a async function (here getapi()) and pass api_url in that function. Define a constant response and store the fetched data by await fetch() method. Define a constant data and store the data in JSON form by await response.json() method. Now we got the data from API by fetch() method in data variable. Pass this data variable to function which will show the data fetched. Function show takes the data variable and by applying for loop on data.list and getting all the rows to show, it stores all the data to tab variable which set the innerHTML property for the class employees in HTML file. I have also added a loader which loads till response comes.
- JavaScript file:
Javascript
// api urlconst api_url =// Defining async functionasyncfunctiongetapi(url) {// Storing responseconst response = await fetch(url);// Storing data in form of JSONvardata = await response.json();console.log(data);if(response) {hideloader();}show(data);}// Calling that async functiongetapi(api_url);// Function to hide the loaderfunctionhideloader() {document.getElementById('loading').style.display ='none';}// Function to define innerHTML for HTML tablefunctionshow(data) {let tab =`<tr><th>Name</th><th>Office</th><th>Position</th><th>Salary</th></tr>`;// Loop to access all rowsfor(let r of data.list) {tab += `<tr><td>${r.name} </td><td>${r.office}</td><td>${r.position}</td><td>${r.salary}</td></tr>`;}// Setting innerHTML as tab variabledocument.getElementById("employees").innerHTML = tab;}chevron_rightfilter_none - HTML file:
HTML
<!DOCTYPE html><htmllang="en"><head><scriptsrc="script.js"></script><linkrel="stylesheet"href="style.css"/><metacharset="UTF-8"/><metaname="viewport"content="width=device-width, initial-scale=1.0"/><title>Document</title></head><body><!-- Here a loader is created whichloads till response comes --><divclass="d-flex justify-content-center"><divclass="spinner-border"role="status"id="loading"><spanclass="sr-only">Loading...</span></div></div><h1>Registered Employees</h1><!-- table for showing data --><tableid="employees"></table></body></html>chevron_rightfilter_none
Output:
- In console ,data in JSON will look like this.

- HTML output.

Recommended Posts:
- JavaScript | fetch() Method
- How to fetch data from JSON file and display in HTML table using jQuery ?
- JavaScript Course | Data Types in JavaScript
- Fetch API
- D3.js d3-Fetch API
- Get and Post method using Fetch API
- How to get the data attributes of an element using JavaScript ?
- How to append data to <div> element using JavaScript ?
- How to get form data using JavaScript/jQuery?
- How to check two objects have same data using JavaScript ?
- How to pass variables and data from PHP to JavaScript ?
- Simple POST request using the fetch API
- How to fetch the details using ng-repeat in AngularJS?
- How to fetch an Integer variable as String in GoLang?
- How to sort element by numerical value of data attribute using JavaScript ?
- How to create data grid for millions of rows in JavaScript ?
- JavaScript | Program to write data in a text File
- How to convert JSON data to a html table using JavaScript/jQuery ?
- How to clear previous appended data on change the dropdown menu in JavaScript ?
- How to make simple PUT request using fetch API by making custom HTTP library ?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


