Updated April 10, 2023
Introduction to JavaScript Fetch API
The JavaScript API which is based on promise to make HTTP requests in the browser which are asynchronous just like the XMLHttpRequest (XHR) is called Fetch API in JavaScript. It is very clean and simple API which makes use of promise feature to deliver a powerful and flexible feature set to bring the resources from the server. Fetch API is supported by all the modern browsers except the Internet Explorer and if there is a necessity to make this Fetch API feature to work on Internet Explorer as well. The addition of polyfill released github to the project we are working on, enables us to work on Internet Explorer.
Usage of Fetch API in JavaScript
The usage of Fetch API in JavaScript can be divided into three sections.
1. Sending a Request
- One parameter can be passed to the fetch() method which is most of the time the URL of the web page or the resource we are trying to fetch.
- The fetch() method then returns a promise which can be handled by using then() and catch() methods.
- The requested resource or the web page contents is available once the request is complete.
- And once the request is complete, the promise is resolved into a response object.
The process of sending a request can be demonstrated as below:
Code:
let response = fetch(url);
fetch(url)
.then(response =>
{
// response is handled
}
)
.catch(error =>
{
//error is handled
}
);
2. Reading the Response
- text() method can be used if the response of the content is in the form of raw text.
- A promise is returned by the text() method that gets resolved displaying the complete contents of the fetched web page contents or the resource.
- async or await can also be used on the returned response.
The process of reading the response can be demonstrated as below using text() method:
Code:
fetch('filename.txt')
.then(response => response.text())
.then(data => console.log(data));
- The process of reading the response can be demonstrated as below using async/await:
Code:
async function fetch()
{
let response = await fetch('filename.txt');
let data = await response.text();
console.log(data);
}
3. Handling the Status Codes Returned by the Response
- Status code and status text is provided by the response object through the properties of status and statusText.
- 200 is the status code and OK is the status text returned by the response object when the status is successful.
- 400 is the status code and Not Found is the status text returned by the response object when the requested web page or the resource do not exist.
- 500 is the status code returned by the response object when the server error is thrown by the URL requested.
Examples of JavaScript Fetch API
Given below are the examples of JavaScript Fetch API:
Example #1
JavaScript program to demonstrate Fetch API to fetch the user first name and the user ID of the corresponding user from the URL passed to the Fetch API method.
Code:
//fetch method is used to read the contents of the web page whose URL is passed as a parameter to the fetch method. Here we are passing the URL which consists of the list of user details like user ID, user first name, user last name etc.
fetch('https://reqres.in/api/users')
//the response from the fetch API is stored in the result variable which is then used to read and display the user first name and user ID alone as the output.
.then(result => result.json())
.then(result =>
{
result.data.map(user =>
{
console.log(` ${user.first_name} is the ${user.id} username `);
});
});
Output:
In the above program, fetch method is used to read the contents of the web page whose URL is passed as a parameter to the fetch method. Here we are passing the URL which consists of the list of user details like user ID, user first name, user last name etc. Then the response from the fetch API is stored in the result variable which is then used to read and display the user first name and user ID alone as the output.
Example 2
JavaScript program to demonstrate Fetch API to fetch the email ID of the corresponding user from the URL passed to the Fetch API method and display the user first name and email ID of the user.
Code:
//fetch method is used to read the contents of the web page whose URL is passed as a parameter to the fetch method. Here we are passing the URL which consists of the list of user details like user ID, user first name, user last name, email ID etc.
fetch('https://reqres.in/api/users')
//the response from the fetch API is stored in the result variable which is then used to read and display the user first name and email ID alone as the output.
.then(result => result.json())
.then(result =>
{
result.data.map(user =>
{
console.log(` The email ID of the user ${user.first_name} is ${user.email}`);
});
});
Output:
In the above program, fetch method is used to read the contents of the web page whose URL is passed as a parameter to the fetch method. Here we are passing the URL which consists of the list of user details like user ID, user first name, user last name, email ID etc. Then the response from the fetch API is stored in the result variable which is then used to read and display the user first name and email ID alone as the output.
Advantages
Advantages of using Fetch API in JavaScript:
- The asynchronous requests can be made and the responses can be handled easily by making use of Fetch API method when compared to using XMLHttpRequest.
- Better API can be created by making use of Fetch API in JavaScript as it makes use of the modern features such as promises.
Recommended Articles
This is a guide to JavaScript Fetch API. Here we discuss the introduction, usage of fetch API in JavaScript, examples and advantages. You may also have a look at the following articles to learn more –