Embark on a journey of knowledge! Take the quiz and earn valuable credits.
Take A QuizChallenge yourself and boost your learning! Start the quiz now to earn credits.
Take A QuizUnlock your potential! Begin the quiz, answer questions, and accumulate credits along the way.
Take A Quiz
🧭 What You’ll Learn
In this hands-on chapter, you will learn to:
🛠 Real-World Feature #1:
Fetching and Displaying a List (Posts Example)
One of the most common use cases of an API is fetching and
displaying a list of items such as blog posts, products, or users.
📌 Fetching Posts with
fetch()
js
async
function loadPosts() {
try {
const res = await
fetch('https://jsonplaceholder.typicode.com/posts');
const data = await res.json();
renderPosts(data.slice(0, 10));
} catch (error) {
console.error('Error loading posts:',
error);
}
}
function
renderPosts(posts) {
const container =
document.getElementById('postList');
container.innerHTML = posts.map(post => `
<div class="post">
<h3>${post.title}</h3>
<p>${post.body}</p>
</div>
`).join('');
}
🧱 HTML Structure
html
<div
id="postList"></div>
<button
onclick="loadPosts()">Load Posts</button>
✍️ Real-World Feature #2:
Submitting a Form (Create Post)
Let’s allow users to submit data using a POST request.
📘 HTML Form
html
<form
id="createForm">
<input type="text"
name="title" placeholder="Title" required />
<textarea name="body"
placeholder="Content"></textarea>
<button type="submit">Create
Post</button>
</form>
🔄 JavaScript to Submit
Form
js
document.getElementById('createForm').addEventListener('submit',
async (e) => {
e.preventDefault();
const formData = new FormData(e.target);
const post = {
title: formData.get('title'),
body: formData.get('body'),
userId: 1
};
const res = await
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: { 'Content-Type':
'application/json' },
body: JSON.stringify(post)
});
const data = await res.json();
alert('Post created with ID: ' + data.id);
});
🔎 Real-World Feature #3:
Implementing Search with Query Params
Most APIs support search and filtering via query
parameters.
💡 Search Endpoint Example
http
GET
/api/products?q=shoes&limit=10
🔍 Example: Debounced
Search Input
html
<input
type="text" id="search" placeholder="Search
posts..." />
<ul
id="results"></ul>
js
let
timeout = null;
document.getElementById('search').addEventListener('input',
function (e) {
clearTimeout(timeout);
timeout = setTimeout(() => {
const keyword = e.target.value;
searchPosts(keyword);
}, 300);
});
async
function searchPosts(q) {
const res = await
fetch(`https://jsonplaceholder.typicode.com/posts?title_like=${q}`);
const data = await res.json();
document.getElementById('results').innerHTML
= data.map(p => `<li>${p.title}</li>`).join('');
}
📄 Real-World Feature #4:
Pagination Using Query Parameters
Paginating API results prevents loading massive datasets at
once.
🧱 Example Pagination
Structure
html
<div
id="userList"></div>
<button
onclick="loadUsers(currentPage - 1)">Prev</button>
<button
onclick="loadUsers(currentPage + 1)">Next</button>
js
let
currentPage = 1;
const
limit = 5;
async
function loadUsers(page) {
if (page < 1) return;
currentPage = page;
const res = await
fetch(`https://jsonplaceholder.typicode.com/users?_page=${page}&_limit=${limit}`);
const data = await res.json();
document.getElementById('userList').innerHTML
= data.map(user => `<p>${user.name}</p>`).join('');
}
🔃 Real-World Feature #5:
Updating and Deleting Records
🖊️ PUT (Update)
js
async
function updatePost(id, updatedData) {
const res = await
fetch(`https://jsonplaceholder.typicode.com/posts/${id}`, {
method: 'PUT',
headers: { 'Content-Type':
'application/json' },
body: JSON.stringify(updatedData)
});
const data = await res.json();
console.log('Updated:', data);
}
❌ DELETE
js
async
function deletePost(id) {
const res = await
fetch(`https://jsonplaceholder.typicode.com/posts/${id}`, {
method: 'DELETE'
});
if (res.ok) alert('Post deleted');
}
💬 Displaying Feedback to
Users
State |
How to Handle |
Loading |
Show a spinner or
“Loading…” message |
Success |
Display a
toast/alert/notification |
Error |
Show error message and
retry button |
Empty State |
Display “No
results found” message |
✅ Spinner Example
html
<div
id="loader" style="display:none;">Loading...</div>
js
function
toggleLoading(state) {
document.getElementById('loader').style.display
= state ? 'block' : 'none';
}
🧠 Best Practices for
Building Features with APIs
📊 Feature Table Summary
Feature |
Method |
API Use Case |
Load list |
GET |
GET /posts, GET /users |
Submit form |
POST |
POST /posts |
Search input |
GET |
GET /posts?q=term |
Pagination |
GET |
GET
/posts?_page=2&_limit=10 |
Update item |
PUT |
PUT /posts/:id |
Delete item |
DELETE |
DELETE
/posts/:id |
🧠 Bonus Tips for UX
Improvements
Tip |
Benefit |
Debounce search
inputs |
Reduces API load |
Disable buttons during submission |
Prevents
duplicate actions |
Optimistically
update UI |
Faster feedback before
response |
Use placeholder loaders |
Improves
perceived performance |
✅ Summary
In this chapter, you’ve learned how to:
You’re now equipped to start building real-world
applications that rely heavily on external APIs and live data!
Answer:
API integration in front-end development refers to the process of connecting
the user interface (UI) of a website or application with external data sources
or back-end services using APIs (Application Programming Interfaces), typically
through HTTP requests.
Answer:
You should understand these four primary methods:
Answer:
Both are used to make HTTP requests, but axios is a third-party library that
offers a simpler API, automatic JSON parsing, request cancellation, and better
error handling compared to the native fetch.
Answer:
Answer:
CORS (Cross-Origin Resource Sharing) is a security feature that
restricts web pages from making requests to a different domain. If not
configured properly on the API server, your front-end app may receive a CORS
error when trying to fetch data.
Answer:
Most APIs use token-based authentication (e.g., Bearer tokens or JWTs). After
login, the token is stored (in localStorage or cookies) and sent in the
Authorization header of future requests.
Answer:
Yes, you can use the native fetch() method or axios in a <script> tag,
but beware of CORS issues and avoid exposing sensitive API keys in client-side
code.
Answer:
Use try/catch blocks or .catch() with fetch/axios to gracefully handle errors.
Also show user feedback (e.g., error messages or retry buttons) when something
goes wrong.
Answer:
Refer to the API documentation provided by the API provider. It lists all
available endpoints, their expected request methods, headers, and responses.
Please log in to access this content. You will be redirected to the login page shortly.
LoginReady to take your education and career to the next level? Register today and join our growing community of learners and professionals.
Comments(0)