๐ŸŒ JavaScript

Fetch API in JavaScript โ€” GET, POST and Error Handling

๐Ÿ“… Jun 19, 2026 โฑ 5 min read

fetch is the built-in way to talk to APIs โ€” the skill every project and interview assumes.

GET

async function getUsers() {
  const res = await fetch("https://api.example.com/users");
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

The trap everyone falls into

fetch does not reject on 404 or 500 โ€” only on network failure. A "successful" fetch can still be an error response. Always check res.ok.

POST with JSON

const res = await fetch("/api/students", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ name: "Priya", dept: "CSE" })
});

The full pattern with UI states

async function load() {
  spinner.show();
  try {
    const data = await getUsers();
    render(data);
  } catch (err) {
    showError("Could not load โ€” try again");
  } finally {
    spinner.hide();      // runs on success AND failure
  }
}

Practice with a real API in the Playground โ€” the "Fetch API" template calls a live joke API.

โ† All Articles