Fetch API

Fetch API is used to make server request. The return value is a Promise. This allows us to build simple and clean API calls.

Basic Fetch Request

Example to use Fetch to get data from server

1
2
3
4
fetch("https://jsonplaceholder.typicode.com/todos/1" )
.then(res => res.json())
.then(json => console.log(json))
.catch(err => console.log(err));

output

1
2
3
4
5
6
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}

fetch() method takes a url as the first argument. The return value is a Promise. json() method converts the response to json. It is the most used method.

POST Request

The fetch() method call accepts a second optional parameter. You specify the request options such as method, headers and body using the second parameter.

Example to send a POST message with headers and body.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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(json => console.log(json))
.catch(err => console.log(err));

output

1
2
3
4
5
6
{
id: 101,
title: 'foo',
body: 'bar',
userId: 1
}

Async and await

You can rewrite the fetch request using async/await. This sometimes makes the code easier to understand and maintain. no more .then() chains.

Async function that uses fetch() to make http request

1
2
3
4
5
6
7
8
9
async function getTodo() {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
if(!response.ok) {
throw new Error(`Http error. status:${response.status}`);
} else {
let json = await response.json();
console.log(json);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
async function createPost() {
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
title: "Title",
body: "Body"
})
})
if (!response.ok) {
throw new Error(`Http error. status:${response.status}`);
} else {
let json = await response.json();
console.log(json);
}
}

await blocks execution of the code that follows until the promise fulfills. So you need to be careful when using async/await

Useful Resources