CodeMIRAI
0 XP

fetch and APIs

2 min read 2 runnable examples Quiz included

fetch() makes HTTP requests from JavaScript: loading data from an API, submitting a form, calling your own back end. It returns a promise, so it pairs naturally with await.

A GET request

This example fetches CodeMIRAI's own course list, which is a real JSON file on this site:

your codeawait fetch(url)await res.json()request: GET /api/usersserverfinds the dataresponsestatus: 200 OKheaders: Content-Type: jsonbody: [{"name": "Asha"}]
fetch resolves when the response arrives, even for 404 or 500, so check res.ok before reading the body.
JavaScript
const response = await fetch(location.origin + "/data/tracks.json");
console.log("Status:", response.status, response.ok);

const courses = await response.json();      // parse the body as JSON
console.log("Courses:", courses.length);
for (const c of courses.slice(0, 5)) {
  console.log(`${c.name}: ${c.modules.length} modules`);
}

Two awaits: one for the response to arrive, one for its body to be read and parsed.

Check the status

fetch only rejects when the network fails. A 404 or 500 still fulfills, with response.ok set to false, so check it:

JavaScript
async function getJSON(url) {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error(`HTTP ${response.status} for ${url}`);
  }
  return response.json();
}

try {
  await getJSON(location.origin + "/data/does-not-exist.json");
} catch (err) {
  console.log("Caught:", err.message);
}

Sending data: POST

JavaScript
const response = await fetch("https://api.example.com/feedback", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ rating: 5, comment: "Great lesson!" }),
});
const result = await response.json();

The options object sets the method, the headers, and the body (as a string).

Common status codes

CodeMeaning
200OK
201Created (after a successful POST)
400Bad request: the data you sent was invalid
401 / 403Not signed in / not allowed
404Not found
429Too many requests: slow down
500Server error

CORS

A page can only fetch from another website if that site allows it, through headers known as CORS. Public APIs designed for browsers send those headers; many others don't, in which case the request has to go through your own server.

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.