Fetch API
Written By: Avinash Malhotra
Updated on
What is the Fetch API?
The Fetch API is a modern, Promise-based JavaScript interface for making network requests. It provides a more powerful and flexible feature set than the older XMLHttpRequest (AJAX), simplifying how we get and post data from web servers and REST APIs.
With Fetch, you can send or receive data in various formats like JSON, Text, and HTML without reloading the entire webpage. It has become the standard for asynchronous data fetching in modern web development.
Introduced in ES6, the Fetch API is supported by all major browsers since 2017. For legacy browsers like Internet Explorer, XMLHttpRequest remains a fallback option.
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 |
How to Use the fetch() Method
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
fetch(req).then(res=>res.text()).then(res=>console.log(res));
Understanding the 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 get method
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)});
Handling Responses
The `fetch()` method returns a Promise that resolves to the `Response` object representing the response to your request. A key detail is that `fetch()` only rejects a promise for a network failure, not for HTTP errors like 404 (Page Not Found) or 500 (Internal Server Error). For HTTP errors, the promise still resolves, and you must check the `response.ok` or `response.status` properties to handle them.
In the example below, `data.txt` is a text file in the 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));
Error Handling with Fetch
Because `fetch()` doesn't reject on HTTP errors like 404, you need to check the response status manually. A common pattern is to check `response.ok` and throw an error if it's `false`.
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok: ' + response.statusText);
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('There was a problem with your fetch operation:', error);
});
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);
})
});
Practical Example: Building a Weather App
In this example, we are using the Fetch API to get live weather data for a city. To use this API, you'll need to get a free API key from OpenWeatherMap. An API Key is required.
const city="delhi";
const appid="YOUR_API_KEY"; // Replace with your OpenWeatherMap API key
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));