Fetch API — GET, POST, PUT, DELETE
The Fetch API is the modern way to make HTTP requests — replacing XMLHttpRequest. It returns Promises and supports all HTTP methods. You'll use fetch for every API interaction in modern web development.
Fetch API
- fetch(url) — Makes HTTP GET request. Returns a Promise that resolves to Response object
- response.json() — Parses JSON body. Also a Promise: await response.json()
- response.ok — true if status 200-299. Check this! fetch doesn't reject on 404/500
- POST/PUT/DELETE — Pass options: fetch(url, { method: 'POST', body: JSON.stringify(data), headers: {...} })
- Headers — { 'Content-Type': 'application/json' } for sending JSON data
- Error handling — fetch only rejects on network errors, NOT on HTTP errors (404, 500). Always check response.ok
Fetch API Code
// GET request
async function getUsers() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
// ⚠️ fetch doesn't throw on 404/500! Check manually
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const users = await response.json();
console.log("Users:", users.slice(0, 3).map(u => u.name));
} catch (error) {
console.error("Failed to fetch:", error.message);
}
}
getUsers();
// POST request — send data
async function createPost(title, body) {
const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title, body, userId: 1 }),
});
const data = await response.json();
console.log("Created:", data);
}
createPost("My Post", "This is the body");
// Reusable API helper
async function api(endpoint, options = {}) {
const baseURL = "https://jsonplaceholder.typicode.com";
const config = {
headers: { "Content-Type": "application/json" },
...options,
body: options.body ? JSON.stringify(options.body) : undefined,
};
const response = await fetch(`${baseURL}${endpoint}`, config);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
}
// Usage
api("/posts/1").then(post => console.log("Post:", post.title));
// api("/posts", { method: "POST", body: { title: "New" } });
// api("/posts/1", { method: "DELETE" });Tip
Tip
Always check response.ok after fetch. A 404 or 500 response doesn't throw an error — you must check: if (!response.ok) throw new Error(response.status). This is the most common fetch mistake.
Fetch does NOT reject on 404/500. Check response.ok.
Common Mistake
Warning
Forgetting that fetch only rejects on network errors, not HTTP errors. fetch('bad-url') with a 404 response still resolves. Check response.ok or response.status before processing the data.
Practice Task
Note
Fetch API: (1) GET data from JSONPlaceholder /users endpoint. (2) POST new data with JSON body and proper headers. (3) Handle both network errors and HTTP errors with different messages. (4) Add a loading indicator.
Quick Quiz
Key Takeaways
- The Fetch API is the modern way to make HTTP requests — replacing XMLHttpRequest.
- fetch(url) — Makes HTTP GET request. Returns a Promise that resolves to Response object
- response.json() — Parses JSON body. Also a Promise: await response.json()
- response.ok — true if status 200-299. Check this! fetch doesn't reject on 404/500