Fetch API
fetch, JSON, REST API calls, error handling
Skills taught: js.fetch, js.http, js.json, js.rest-api
GET request — fetching data
async function loadUser(id) {
try {
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
// fetch ONLY throws on network errors — check HTTP status manually
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const user = await response.json(); // parse JSON body
console.log(user.name, user.email);
return user;
} catch (error) {
console.error('Failed to load user:', error.message);
return null;
}
}
loadUser(1);
POST request — sending data
async function createPost(postData) {
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json', // tell server we're sending JSON
},
body: JSON.stringify(postData), // convert object to JSON string
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const created = await response.json(); // server returns the created resource
console.log('Created post with id:', created.id);
return created;
}
createPost({
title: 'Learning KERNAL',
body: 'JavaScript is amazing!',
userId: 1,
});
PUT, PATCH, DELETE
const BASE = 'https://jsonplaceholder.typicode.com';
const headers = { 'Content-Type': 'application/json' };
// PUT — replace entire resource
await fetch(`${BASE}/posts/1`, {
method: 'PUT',
headers,
body: JSON.stringify({ title: 'Updated', body: 'New body', userId: 1 }),
});
// PATCH — update specific fields
await fetch(`${BASE}/posts/1`, {
method: 'PATCH',
headers,
body: JSON.stringify({ title: 'Only title changed' }),
});
// DELETE — remove resource
const res = await fetch(`${BASE}/posts/1`, { method: 'DELETE' });
console.log(res.ok); // true if successful (204 No Content)
A reusable fetch helper
// A thin wrapper that handles errors and JSON automatically
async function api(path, options = {}) {
const response = await fetch(`https://api.example.com${path}`, {
headers: { 'Content-Type': 'application/json', ...options.headers },
...options,
body: options.body ? JSON.stringify(options.body) : undefined,
});
if (!response.ok) {
const err = await response.json().catch(() => ({}));
throw new Error(err.message ?? `HTTP ${response.status}`);
}
// 204 No Content — no body to parse
if (response.status === 204) return null;
return response.json();
}
// Usage
const user = await api('/users/1');
const post = await api('/posts', { method: 'POST', body: { title: 'Hello' } });
await api('/posts/1', { method: 'DELETE' });
Frequently Asked Questions
What is CORS and why does it block my fetch requests?
CORS (Cross-Origin Resource Sharing) is a browser security rule that blocks requests to a different domain unless the server explicitly allows it. If you see a CORS error, the server needs to add Access-Control-Allow-Origin headers. You can't fix CORS on the client side — it must be configured on the server.
What is the difference between fetch and axios?
fetch is built-in (no install needed). axios auto-parses JSON, throws on HTTP errors, supports request cancellation, and has interceptors. For simple uses, fetch is fine. For production apps with auth, retries, and complex error handling, axios or React Query/SWR adds value.