JavaScript Lesson 8: Fetch β€” Getting Data From an API

JavaScript Lesson 8: Fetch β€” Getting Data From an API featured illustration

πŸ“Ž This article includes 2 downloadable practice files ↓

⏱ 1 min read

πŸ“˜ JavaScript Beginner Course Β· Lesson 8 of 8

Advertisement
async function main() {
  try {
    const res = await fetch("https://jsonplaceholder.typicode.com/users?_limit=3");
    if (!res.ok) throw new Error("HTTP " + res.status);
    const users = await res.json();
    users.forEach(u => console.log(u.id, u.name, u.address.city));
  } catch (e) {
    console.log("Could not fetch:", e.message);
  }
}
main();
  • fetch returns a promise; await waits for it inside an async function.
  • Check res.ok: a 404 or 500 doesn’t throw by itself.
  • res.json() parses the body.
⚠️ Never put secret API keys in browser JavaScript; anyone can read them. Call keyed APIs from a server or a script running only on your machine.
πŸ’‘ Browsers block calls to other sites unless the API allows it (CORS). If fetch works in Node but fails in the browser, that’s usually why.

That’s the JavaScript course.

Practice

Run the script with internet on, then off, to see the error handling.

Advertisement

πŸ“Ž Practice files for this article

⬇ Download all 2 files (ZIP Β· 632 B)

Free to use for learning. Files with macros (.bas) are plain text β€” import them with Alt+F11 β†’ File β†’ Import File, and always test on a copy.

✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free Β· AI can be wrong