Tools: Mastering the Fetch API with Real‑Life JavaScript Examples

Tools: Mastering the Fetch API with Real‑Life JavaScript Examples

Source: Dev.to

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) 🔹 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) 🧠 What is URLSearchParams? It converts an object into a valid query string: 🔹 Real‑life use: Filtering, pagination, sorting, embedding relations. 3️⃣ Updating Data (PUT vs PATCH)
PUT (Replace Entire Object) PATCH (Partial Update – Recommended) 🔹 Real‑life use: Updating profile info, settings, preferences. 4️⃣ Deleting a User (DELETE) ✅ Empty object {} is NORMAL for DELETE responses. 5️⃣ Reusable Requests with new Request() 🔹 Why use new Request()? Middleware‑style patterns Better for large apps 6️⃣ Aborting Requests with AbortController Cancel search requests Prevent race conditions Templates let you quickly answer FAQs or store snippets for re-use. Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink. Hide child comments as well For further actions, you may consider blocking this person and/or reporting abuse CODE_BLOCK:
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: '[email protected]',
}); Enter fullscreen mode Exit fullscreen mode CODE_BLOCK:
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: '[email protected]',
}); CODE_BLOCK:
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: '[email protected]',
}); CODE_BLOCK:
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 CODE_BLOCK:
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(); CODE_BLOCK:
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(); CODE_BLOCK:
{ _embed: 'posts' } → _embed=posts Enter fullscreen mode Exit fullscreen mode CODE_BLOCK:
{ _embed: 'posts' } → _embed=posts CODE_BLOCK:
{ _embed: 'posts' } → _embed=posts CODE_BLOCK:
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 CODE_BLOCK:
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());
} CODE_BLOCK:
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());
} CODE_BLOCK:
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 CODE_BLOCK:
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' }); CODE_BLOCK:
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' }); CODE_BLOCK:
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 CODE_BLOCK:
async function deleteUser(userId) {
const res = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`, {
method: 'DELETE',
}); console.log(await res.json()); // {}
} deleteUser(5); CODE_BLOCK:
async function deleteUser(userId) {
const res = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`, {
method: 'DELETE',
}); console.log(await res.json()); // {}
} deleteUser(5); CODE_BLOCK:
async function adminDashboard(request) {
const res = await fetch(request);
const data = await res.json();
console.log(data);
} Enter fullscreen mode Exit fullscreen mode CODE_BLOCK:
async function adminDashboard(request) {
const res = await fetch(request);
const data = await res.json();
console.log(data);
} CODE_BLOCK:
async function adminDashboard(request) {
const res = await fetch(request);
const data = await res.json();
console.log(data);
} CODE_BLOCK:
const addUser = new Request('https://jsonplaceholder.typicode.com/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Hamza Chy', email: '[email protected]' }),
}); adminDashboard(addUser); Enter fullscreen mode Exit fullscreen mode CODE_BLOCK:
const addUser = new Request('https://jsonplaceholder.typicode.com/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Hamza Chy', email: '[email protected]' }),
}); adminDashboard(addUser); CODE_BLOCK:
const addUser = new Request('https://jsonplaceholder.typicode.com/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Hamza Chy', email: '[email protected]' }),
}); adminDashboard(addUser); CODE_BLOCK:
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 CODE_BLOCK:
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); CODE_BLOCK:
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); CODE_BLOCK:
const deleteUser11 = new Request('https://jsonplaceholder.typicode.com/users/11', {
method: 'DELETE',
}); adminDashboard(deleteUser11); Enter fullscreen mode Exit fullscreen mode CODE_BLOCK:
const deleteUser11 = new Request('https://jsonplaceholder.typicode.com/users/11', {
method: 'DELETE',
}); adminDashboard(deleteUser11); CODE_BLOCK:
const deleteUser11 = new Request('https://jsonplaceholder.typicode.com/users/11', {
method: 'DELETE',
}); adminDashboard(deleteUser11); CODE_BLOCK:
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 CODE_BLOCK:
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');
} CODE_BLOCK:
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');
}