The Fetch API is a promise-based interface for fetching resources by making HTTP requests to servers from web browsers. It is similar to XML HTTP requests but better and more powerful.
Fetch API comes with a fetch () method that allows you to fetch data from all sorts of different places and work with the data fetched. It allows you to make an HTTP request, i.e., either a GET request (for getting data) or POST request (for posting data).
The basic fetch request can be explained by the following code:
1
2
3
4
5
6
7
8
9
10
11
12
fetch('url')
.then(response => {
//handle response
console.log(response);
})
.then(data => {
//handle data
console.log(data);
})
.catch(error => {
//handle error
});
The fetch() method has two parameters. The path to the resource is the first parameter and is required all the time, whereas the init parameter is optional. It then returns a promise that resolves into a response object. The response object further contains the data that needs to be converted into the required format in order to work with it. However, we must handle the HTTP errors as the promise only rejects network errors.
const response=fetch( URL [, init])
URL: a URL object that represents the path of the resource to be fetched
Init (optional): Any further options such as:
Method: The request method is either GET or POST.
Headers
Body: The body can be any of the following: Body.array.Buffer(), Body.Blob(), Body.formData(), Body.json(), Body.text().
Mode
Credentials
Cache
1 2 3 4 5 6 7 8 9
fetch('url', { Method: 'POST', Headers: { Accept: 'application.json', 'Content-Type': 'application/json' }, Body: body, Cache: 'default' })
As discussed, we know that HTTP errors must be handled by using the response object properties Response.ok and Response.status. Response.ok is a Boolean value that lets us know if the response was successful or not, whereas Response.status represents the HTTP status codes, such as 200 for success and 404 if the resource is not found. Have a look at the following response object:
Let us look at a simple example of fetching an image which makes it easier to understand the concept. The steps involved will be:
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
</head>
<body>
<img src="" id="flower" width=400 height=400/>
<script>
console.log("about to fetch a flower");
GetImage().catch(error => {
console.error(error);
});
async function GetImage(){
const response = await fetch('/anim.jpg');
const blob = await response.blob();
document.getElementById('flower').src=URL.createObjectURL(blob);
}
</script>
</body>
</html>
Explanation:
In the above example, we are using the async/await keyword that allows us to deal with promises in a readable and clean way. We are then using a function URL.createObjectURL()
method that creates a DOMString containing a URL representing the object. Finally, we create an IMG element and place the data fetched into the <img> element.
Example 2: Fetching JSON data and displaying in an HTML table
In this example, we are extracting the JSON data fetched from a live API (https://www.thecocktaildb.com/) which is an open crowd-sourced database of drinks and cocktails from around the world. Let us look at the JSON data we have received in the console.
The dataset has many properties and in this example I am displaying two properties, the drink name(strDrink) and instructions(strInstructions), in an HTML table as shown in the output. We are adding a table element in our HTML and then iterating through the JSON data and adding them to the table (i.e., data.drinks[i].strDrink and data.drinks[i].strInstructions).
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<table class="table table-bordered">
<tbody id="data">
</tbody>
</table>
<script>
getData();
async function getData(){
const response= await fetch('https://www.thecocktaildb.com/api/json/v1/1/search.php?s=margarita%’)
console.log(response);
const data= await response.json();
console.log(data);
length=data.drinks.length;
console.log(data);
var temp="";
for(i=0;i<length;i++)
{
temp+="<tr>";
temp+="<td>"+data.drinks[i].strDrink+"</td>";
temp+="<td>"+data.drinks[i].strInstructions+"</td>";
}
document.getElementById("data").innerHTML=temp;
}
</script>
</body>
</html>
Output:
So far, we have discussed two examples for fetching data. The Fetch API not only provides us with a GET request, but it also provides us with POST, PUT and DELETE requests. Let us now look at a simple example of posting JSON data. For doing so, we are using an endpoint https://jsonplaceholder.typicode.com/guide/. Let us look at the JSON data in this endpoint:
1
2
3
4
5
6
7
8
9
10
11
Object {
title: "",
body: "",
id: 101
}
body: ""
id: 101
title: ""
We are creating a simple form for getting the title and body from the user in the HTML part. Note that the ID is automatically generated. Coming to the script, we are adding an event listener function and then calling the fetch method. In the fetch method, we are providing the URL of the endpoint and a configuration object. Finally we are displaying the data we have posted in our HTML elements <h4> and <h5>.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
<html> <head> </head> <body> <form id="form" method="post"> <input type="text", id="name" placeholder="Name"/></br> <input type="text", id="body" placeholder="Body"/></br> <input type="submit" value="Add"/> </form> <div> <h3>The Following data is successfuly posted</h3> <h4 id="title"></h4> <h5 id="bd"></h5> </div> </body> <script> var form=document.getElementById('form') form.addEventListener('submit', function(e){ e.preventDefault() var name=document.getElementById('name').value var body=document.getElementById('body').value fetch('https://jsonplaceholder.typicode.com/posts', { method: 'POST', body: JSON.stringify({ title:name, body:body, }), headers: { 'Content-type': 'application/json; charset=UTF-8', } }) .then(function(response){ return response.json()}) .then(function(data) {console.log(data) title=document.getElementById("title") body=document.getElementById("bd") title.innerHTML = data.title body.innerHTML = data.body }).catch(error => console.error('Error:', error)); }); </script> </html>
Output:
The JSON response as observed in the console:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Object {
title: "john",
body: "John is an engineer",
id: 101
}
body: "John is an engineer"
id: 101
title: "john"
<
prototype >: Object {
…}