Guide

How to Call a Free API in JavaScript (fetch, Errors & CORS โ€” Explained Simply)

Every web app you admire is, under the hood, asking other computers for data and showing the answer. That asking is an API call, and in JavaScript it takes four lines:

const res = await fetch("https://catfact.ninja/fact");
const data = await res.json();
console.log(data.fact);

That code is live, real and free โ€” paste it into any browser console and it works. You just used your first API. Everything else is refinement.

Step 1 โ€” pick an API that needs no key

Keys are for later. Start with a keyless API from our no-key list โ€” Open-Meteo for weather, PokeAPI for game data, JSONPlaceholder for practice. Copy its endpoint, change the interesting part (the city, the name, the id), and watch the answer change.

Step 2 โ€” handle the wait and the failure

APIs are other people's computers: sometimes slow, sometimes down. Real code wraps the call:

async function getFact() {
  try {
    const res = await fetch("https://catfact.ninja/fact");
    if (!res.ok) throw new Error("HTTP " + res.status);
    const data = await res.json();
    return data.fact;
  } catch (err) {
    return "The API is napping: " + err.message;
  }
}

Step 3 โ€” understand CORS (the error everyone meets)

If your console ever screams No 'Access-Control-Allow-Origin' header, that is CORS: the API's server telling your browser "I don't serve web pages, only apps". It is not your bug. Three escapes: pick an API marked CORS โœ“ in our catalog (that badge exists precisely for this), call the API from your own tiny backend, or test it in our playground first to see the data shape.

Your next hour

Congratulations โ€” you are now an API developer. The other 113 APIs in the catalog all work exactly like this.

Done