In this article, I will guide you on how to use Fetch API in Javascript.

Note: I am using Free fake API for testing and prototyping for demo URL: JSONPlaceholder.

So, let's get started,

fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

This code fetches data from the specified URL and logs the response data to the console. The fetch() method returns a promise that resolves to a Response object. We then use the json() method on the response object to extract the JSON data from the response.

Fetch data with Get Request

fetch('https://jsonplaceholder.typicode.com/posts',{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

Send data using Post Request

fetch('https://jsonplaceholder.typicode.com/posts/999')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

Error Handling

Error in console

async function fetchUserData(userId) {
const response = await
fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
const data = await response.json();
return data;
}

fetchUserData(10)
.then(data => console.log(data))
.catch(error => console.error(error));

Async and Await

const headers = new Headers();
headers.append('Authorization','Bearer token');
fetch('API URL', {
headers: headers
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));