⚡ Lesson 20 of 30
Fetch API & REST Calls
Communicate with web servers using the Fetch API — GET, POST, error handling, and headers.
Basic GET Request
async function getPost(id) {
const response = await fetch(
`https://jsonplaceholder.typicode.com/posts/${id}`
);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const post = await response.json();
console.log(post.title);
}
getPost(1);
POST Request
async function createPost(data) {
const response = await fetch(
"https://jsonplaceholder.typicode.com/posts",
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
}
);
const created = await response.json();
console.log("Created ID:", created.id);
}
createPost({ title:"Hello", body:"World", userId:1 });
Error Handling
Note: fetch only rejects on network failure — not on HTTP 4xx/5xx. Always check response.ok:
async function safeFetch(url) {
try {
const res = await fetch(url);
if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
return await res.json();
} catch (err) {
console.error("Fetch failed:", err.message);
return null;
}
}
Request with Auth Headers
const TOKEN = "your_api_token_here";
async function getSecure(url) {
const res = await fetch(url, {
headers: {
"Authorization": `Bearer ${TOKEN}`,
"Accept": "application/json",
}
});
return res.json();
}
Abort & Timeout
Cancel a fetch request that takes too long:
async function fetchWithTimeout(url, ms = 5000) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), ms);
try {
const res = await fetch(url, { signal: controller.signal });
return await res.json();
} catch (e) {
if (e.name === "AbortError") console.error("Request timed out");
throw e;
} finally {
clearTimeout(timer);
}
}