JavaScript Lesson 8: Fetch — Getting Data From an API

📎 This article includes 2 downloadable practice files ↓

⏱ 1 min read

📘 JavaScript Beginner Course · Lesson 8 of 8

“`javascript
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.

📎 Practice files for this article

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