DEV Community

Mahmudul Fahim
Mahmudul Fahim

Posted on

Mastering the Fetch API with Real‑Life JavaScript Examples

If you’re learning JavaScript seriously, the Fetch API is not optional — it’s a core skill for real-world frontend development.

In this post, I’ll walk you through everything I practised in one single playground, including:

GET, POST, PUT, PATCH, DELETE

Handling JSON responses

Using URLSearchParams

Creating reusable requests with new Request()

Aborting requests with AbortController

Simulating file downloads

All examples use the free fake API: https://jsonplaceholder.typicode.com

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',
});
Enter fullscreen mode Exit fullscreen mode

🔹 Real‑life use: Signup forms, admin dashboards, and adding new records.

⚠️ JSONPlaceholder does NOT save 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();
Enter fullscreen mode Exit fullscreen mode

🧠 What is URLSearchParams?

It converts an object into a valid query string:

{ _embed: 'posts' } → _embed=posts
Enter fullscreen mode Exit fullscreen mode

🔹 Real‑life use: Filtering, pagination, sorting, embedding relations.

3️⃣ Updating Data (PUT vs PATCH)
PUT (Replace Entire Object)

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());
}
Enter fullscreen mode Exit fullscreen mode

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' });
Enter fullscreen mode Exit fullscreen mode

🔹 Real‑life use: Updating profile info, settings, 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);
Enter fullscreen mode Exit fullscreen mode

✅ 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);
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Delete Request

const deleteUser11 = new Request('https://jsonplaceholder.typicode.com/users/11', {
method: 'DELETE',
});


adminDashboard(deleteUser11);
Enter fullscreen mode Exit fullscreen mode

🔹 Why use new Request()?

Cleaner architecture

Reusable requests

Middleware‑style patterns

Better for large apps

6️⃣ Aborting Requests with AbortController



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');
}
Enter fullscreen mode Exit fullscreen mode

🔹 Real‑life use:

Cancel search requests

Stop downloads

Prevent race conditions

Top comments (0)