JavaScript Tutorial in Hindi #32 | Fetch API with Real Project(2025)

Practical Project: Simple API Call Project

Goal:

Fetch a post from an API and show its title and body on the page when the user clicks a button.

Complete Code (HTML + CSS + JS):

html
CopyEdit
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Simple API Call Project</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 40px auto;
padding: 0 20px;
background: #f0f0f0;
color: #333;
}
button {
padding: 10px 20px;
font-size: 1.1rem;
cursor: pointer;
margin-bottom: 20px;
}
.post {
background: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 8px rgba(0,0,0,0.1);
}
.post h2 {
margin-top: 0;
}
</style>
</head>
<body>

<h1>Simple API Call Project</h1>
<button id="loadPostBtn">Load Post</button>
<div class="post" id="postContainer">
<p>Click the button to load a post.</p>
</div>

<script>
const button = document.getElementById('loadPostBtn');
const postContainer = document.getElementById('postContainer');

button.addEventListener('click', () => {
// Clear previous content
postContainer.innerHTML = '<p>Loading...</p>';

fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(post => {
postContainer.innerHTML = `
<h2>${post.title}</h2>
<p>${post.body}</p>
`;
})
.catch(error => {
postContainer.innerHTML = `<p style="color:red;">Failed to load post. Try again later.</p>`;
console.error('Fetch error:', error);
});
});
</script>

</body>
</html>

How It Works:

  1. User clicks Load Post button.
  2. Button click triggers fetch to JSONPlaceholder API (a fake REST API for testing).
  3. Shows “Loading…” message while waiting.
  4. On success, displays post title and body.
  5. On failure, shows error message.