What is Fetch API?
The Fetch API is a modern JavaScript API used to make HTTP requests to a server.
It allows us to perform operations such as:
GET → Read data
POST → Create data
PUT → Update complete data
PATCH → Update partial data
DELETE → Delete data
The Fetch API returns a Promise, so we can handle the response using .then() and .catch().
Basic Syntax:
fetch(url)
.then(response => response.json())
.then(data => { console.log(data); })
.catch(error => { console.log(error); });
How Fetch API Works?
JavaScript
↓
fetch()
↓
HTTP Request
↓
Server / API
↓
HTTP Response
↓
response.json()
↓
JavaScript Data
For example:
fetch("https://fakestoreapi.com/products")
The browser sends a request to the API.
The API sends a response.
We then convert the response into JavaScript data using:
response.json();
Response Object:
fetch(url)
.then(response => {
console.log(response);
});
response is a Response object.
It contains useful information such as:
- response.status
- response.ok
- response.headers
- response.json()
For example:
fetch("https://fakestoreapi.com/products")
.then(response => {
console.log(response.status);
console.log(response.ok);
});
A successful response may have:
status → 200
ok → true
What Happens Internally?
When we execute:
fetch(url)
the following process happens:
- fetch() is called ↓
- Browser sends HTTP request ↓
- JavaScript continues executing ↓
- Server processes request ↓
- Server sends response ↓
- Promise is fulfilled ↓
- .then() executes ↓
- response.json() converts JSON ↓
- Next .then() receives the data
This is why Fetch API is useful for performing asynchronous operations without blocking the main JavaScript execution.
Fetch API vs XMLHttpRequest
Before Fetch API, developers commonly used XMLHttpRequest.
XMLHttpRequest
let xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = function() {
console.log(xhr.responseText);
};
xhr.send();
Fetch provides a more modern Promise-based approach:
fetch(url)
.then(response => response.json())
.then(data => console.log(data));
So Fetch API generally provides a cleaner way to work with HTTP requests.
Top comments (0)