JavaScript Tutorial in Hindi #31 | Fetch API (2025)

✅ 1. What is Fetch API?

  1. Fetch API is a modern way to make network requests in JavaScript.
  2. It replaces older methods like XMLHttpRequest.
  3. Uses Promises for easier asynchronous code.
  4. Commonly used to get or send data from/to servers (APIs).

✅ 2. Basic Fetch Request (GET Request)

js
CopyEdit
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json()) // Parse JSON from response
.then(data => {
console.log(data); // Use the data
})
.catch(error => {
console.error('Error:', error);
});

✅ 3. Fetch with POST Request (Send Data)

js
CopyEdit
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST', // HTTP method
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1,
}),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch(error => {
console.error('Error:', error);
});

✅ 4. Handling Responses and Errors

  1. Always check if response is OK (response.ok).
  2. Handle network or server errors in .catch.
  3. Example with error check:
js
CopyEdit
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.status);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Fetch error:', error));

✅ 5. Practical Example – Simple API Call Project

HTML:

html
CopyEdit
<button id="loadData">Load Post</button>
<div id="post"></div>

JavaScript:

js
CopyEdit
document.getElementById('loadData').addEventListener('click', () => {
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(post => {
document.getElementById('post').textContent = post.title;
})
.catch(error => {
document.getElementById('post').textContent = 'Failed to load data';
console.error(error);
});
});

Clicking the button fetches a post title and displays it.