Mastering the Fetch API with Real‑Life JavaScript Examples
Source: Dev.to
If you’re learning JavaScript seriously, the Fetch API is a core skill for real‑world frontend development. All examples use the free fake API: .
1️⃣ Creating a User (POST Request)
async function createUser(userData) {
const api_url = 'https://jsonplaceholder.typicode.com/users';
const res = await fetch(api_url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(userData),
});
const data = await res.json();
console.log(data);
}
createUser({
id: crypto.randomUUID(),
name: 'Md Fahim',
email: 'mdfahim@gmail.com',
});
- Real‑life use: Signup forms, admin dashboards, and adding new records.
- Note: JSONPlaceholder does not persist data; it only simulates a response.
2️⃣ Fetch Users With Related Data (URLSearchParams)
async function fetchUsersWithPosts() {
const api_url = 'https://jsonplaceholder.typicode.com/users';
const queryParams = { _embed: 'posts' };
const queryString = new URLSearchParams(queryParams).toString();
const res = await fetch(`${api_url}?${queryString}`);
const data = await res.json();
console.log(data);
}
fetchUsersWithPosts();
What is URLSearchParams?
It converts an object into a valid query string, e.g. { _embed: 'posts' } → _embed=posts`.
- Real‑life use: Filtering, pagination, sorting, embedding related resources.
3️⃣ Updating Data (PUT vs PATCH)
PUT (Full Update)
async function putUser(data) {
const res = await fetch('https://jsonplaceholder.typicode.com/users/1', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
console.log(await res.json());
}
PATCH (Partial Update – Recommended)
async function patchUser(data) {
const res = await fetch(`https://jsonplaceholder.typicode.com/users/${data.id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
console.log(await res.json());
}
patchUser({ id: 3, name: 'Alex Smith' });
- Real‑life use: Updating profile information, settings, or preferences.
4️⃣ Deleting a User (DELETE)
async function deleteUser(userId) {
const res = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`, {
method: 'DELETE',
});
console.log(await res.json()); // {}
}
deleteUser(5);
✅ An empty object {} is normal for DELETE responses.
5️⃣ Reusable Requests with new Request()
async function adminDashboard(request) {
const res = await fetch(request);
const data = await res.json();
console.log(data);
}
/* Create Request */
const addUser = new Request('https://jsonplaceholder.typicode.com/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Hamza Chy', email: 'hamza@gmail.com' }),
});
adminDashboard(addUser);
/* Update Request */
const updateUser = new Request('https://jsonplaceholder.typicode.com/users/11', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Hamza Chowdhury' }),
});
adminDashboard(updateUser);
/* Delete Request */
const deleteUser11 = new Request('https://jsonplaceholder.typicode.com/users/11', {
method: 'DELETE',
});
adminDashboard(deleteUser11);
Why use new Request()?
- Cleaner architecture
- Reusable request objects
- Middleware‑style patterns
- Better suited for large applications
6️⃣ Aborting Requests with AbortController
let controller; // will hold the AbortController instance
async function downloadFile() {
controller = new AbortController();
const res = await fetch('./download/file.txt', {
signal: controller.signal,
});
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'file.txt';
a.click();
URL.revokeObjectURL(url);
}
function abortDownload() {
controller.abort('User cancelled download');
}
- Real‑life use: Canceling search requests, stopping file downloads, preventing race conditions.