Fetch API
Written By: Avinash Malhotra
Updated on
Fetch API
Fetch API is Promise based api used to fetch data across web server, almost same like AJAX but with easy syntax and more features.
Fetch API can also send or receive data like XML, JSON, TEXT and HTML from web server like AJAX without reloading webpage. Fetch is also used to fetch data from Web API or REST APIs.
Fetch api was introduced in JS ES6. For IE and legacy browser, we can still use XMLHttpRequest. Fetch is supported in all major browsers since 2017.
Fetch Vs Ajax
Properties | Fetch | Ajax ( xhr) |
---|---|---|
ECMA Version | ES6 | ES5 |
Architecture | Promise based | Event Based |
Complexity | Easy | Complex |
Syntax | Simple | Verbose |
Request / Response | Supports | Supports but complex structure |
Cookies | use cookies | Cookie less |
Fetch
fetch api is based on Request and Response . Request is the incoming stream to server and Response is the outgoing stream from server.
Request is the URL of resource.
then handler is used to get response of request. then includes a callback with Response.
fetch example
fetch(Request)
fetch example with then handler
fetch(req).then(res=>res.text()).then(res=>console.log(res));
Request
Request is the incoming stream to the server. The first Parameter URL is compulsory. Second parameter is optional with options like http method, payload, etc.
Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Response
fetch('data.txt');
fetch with options
Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Response
fetch('data.txt',{method:"GET"});
fetch with post method
Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Response
const data={name:"username"};
fetch('/post',{method:'POST',body:JSON.stringify(data)});
Response
fetch api returns a Promise that resolves to Response of that request. This will even respond to HTTP Errors like 404 () Page not Found or 500 ( Internal Server error). For such errors, the then() handler must check Response.ok or Response.status.
In the example below, data.txt is a text file in root directory.
Response {type: 'basic', url: 'http://127.0.0.1:5501/data.txt', redirected: false, status: 200, ok: true, …}
fetch("data.txt").then(i=>i).then(i=>console.log(i));
Response.text()
Hello Fetch API
fetch("data.txt").then(i=>i.text()).then(i=>console.log(i));
Response.ok
response.ok return boolean value true or false. If the resource is found successfully, the true else false. See examples below.
true
fetch("data.txt").then(i=>i.ok).then(i=>console.log(i));
false
fetch("abc.txt").then(i=>i.ok).then(i=>console.log(i));
Response.status
Response.status return the HTTP Response of request, like 200, 404, 500 etc. See examples below.
200
fetch("data.txt").then(i=>i.status).then(i=>console.log(i));
404
fetch("abc.txt").then(i=>i.status).then(i=>console.log(i));
Fetch text data
To fetch text data, use Response.text() method in first then() handler with callback and Response parameter. This will convert Response data to string. To print string response, use another then() handler with callback and Response parameter.
text from data
fetch("data.txt").then(i=>i.text()).then(i=>document.querySelector(".app").textContent=i);
Fetch JSON data
To fetch JSON data, use Response.json() method in first then() handler with callback and Response parameter. This will convert Response data to JSOn Object. To print JSON response, use another then() handler with callback and Response parameter.
JSON data
fetch("data.json").then(i=>i.json()).then(i=>{
i.forEach(j=>{
console.log(j);
})
});
Weather API
In this example, we are using fetch api to fetch weather data of a city. To use this api, create a free account on openweathermap.com and generate API Key. API Key is compulsory.
const city="delhi";
const appid="6565a145678cc21caccc3df7f2132a1c";
const url=`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${appid}&units=metric`;
fetch(url).then(i=>i.json()).then(i=>console.log(i));