Hello everyone, I hope everyone is safe.
In this blog, we will learn about fetch() API with a simple example.
Prerequisites
A basic understanding of Promises, Async, and Await is required.
What is Fetch API?
- The Fetch API is a modern interface that allows us to make HTTP requests to servers from web browsers.
- And it is much simpler and cleaner, uses promise to deliver more flexible features to make requests to servers from the web browsers.
Let us see sending a request and reading the response.
Sending a Request
The fetch() requires only one parameter which is the URL of the resource that you want to fetch,
let response = fetch(url);
The fetch() method returns a Promise so you can use then() and catch() methods to handle it,
fetch(url)
.then(response => {
// handle the response
})
.catch(error => {
// handle the error
});
Example
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(res => console.log(res));
In the above example,
- When the request completes, the promise will resolve into a Response object.
- The Response object has a number of useful properties and methods to inspect the response
Reading the Response
In practice, we use the async / await with the fetch() method,
async function fetchMethod() {
let response = await fetch(url);
let data = await response.text();
console.log(data);
}
Now let us build a simple application that gives us a clear picture of fetch API using "reqres", a fake data API - https://reqres.in/ - know more here.
Step 1 - Build the Client-Side
<body>
<h1>Fetch API Basics</h1>
<h2>GET Method</h2>
<div class="container">
<!-- Fetch API -->
</div>
<script src="./fetchAPI.js"></script>
</body>
Step 2 - Define the method
getUsers() method will return response data from the API.
renderUsers();
async function renderUsers() {
let users = await getUsers();//Fetch method
}
Step 3 - The fetch() method
async function getUsers() {
let url = 'https://reqres.in/api/users';
try {
let res = await fetch(url);
return await res.json(); //Reading response
} catch (error) {
console.log(error);
}
}
Besides the json() method, the Response object has other methods such as text(), blob(), formData() and arrayBuffer().
Step 4 - Reading and displaying the response data
Full code for renderUsers() method,
async function renderUsers() {
let users = await getUsers();
let htmlContent = '';
let usersLen = users.data.length;
for(var i=0;i<usersLen;i++){
let htmlSegments = `<div class="user"><img src="${users.data[i].avatar}" >
<h2>${users.data[i].first_name} ${users.data[i].last_name}</h2>
<div class="email"><a href="">${users.data[i].email}</a></div> </div>`;
htmlContent += htmlSegments;
}
let container = document.querySelector('.container');
container.innerHTML = htmlContent;
}
Screenshot
To know more, do read the official documentation.
Happy learning!