SyntaxPilot
Courses/Vibe Coding/Lesson 13
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Vibe Coding · Lesson 13 of 40

Project: weather app with a public API

what an API isHTTP requestJSON responsefetchasync/awaitloading and error statesAPI keys and rate limitsenvironment variables (.env)never committing secrets

Vibe Coding: build real apps with AI · Episode 13. Every agent run below is real: Claude Code 2.1.322 (model claude-opus-5-5) in print mode (claude -p), on 11 November 2026, in /home/ravi/projects/weather-app (a Git repository). Every API call was made for real on 11 November 2026 around 15:30 UTC (21:00 in India) with curl and Node.js v22.23.4. The browser screenshots are the AI's real page in Chromium, answered with those exact recorded API responses. Replies are quoted exactly, shortened where marked ....

Facts about Open-Meteo, OpenWeatherMap and fetch were checked on 11 November 2026 against the services' own pages (Open-Meteo terms and geocoding docs, MDN). Free tiers and limits change: check them again before you build.

The problem: umbrella or not?

Ravi is going to a wedding in Kochi, Kerala this weekend. One question: should he pack an umbrella?

Every app we built so far (the to-do list, the expense tracker, the portfolio) only knew what we typed into it. Weather changes every hour, everywhere. We can't type it in. The data lives on someone else's computer, so we need a way for our page to ask that computer.

What an API is (a railway enquiry counter)

Railway enquiry A weather API
you give your PNR number, in the format they want the request: a URL with your question
a fixed list of questions (status, coach, seat) the API's rules: what you may ask and how
a printed status slip, same layout every time the response: data in JSON
you never see their computer room their server is hidden behind the API

An API (application programming interface) is a set of rules for how one program asks another program for something.

The question is written in the URL

https://api.open-meteo.com/v1/forecast?latitude=28.65&longitude=77.23&current=temperature_2m
└──────── server ────────┘└ endpoint ┘└────────────── query parameters ──────────────┘
  • Endpoint: one "counter", one kind of question (/v1/forecast).
  • Query parameters: after the ?, pairs of name=value, joined with &.
  • Opening the URL sends an HTTP request. HTTP is the set of rules browsers and servers use to ask and answer. A GET request means "give me this".

Open-Meteo (checked 11 Nov 2026, open-meteo.com/en/terms): the free API is "only for non-commercial purposes", with "less than 10'000 API calls per day, 5'000 per hour and 600 per minute". No account and no API key are needed. The data is under the CC-BY 4.0 licence, so credit Open-Meteo (the AI's page does: "Data from Open-Meteo").

Asking with curl (real)

curl is a free command-line tool that sends a request and prints the answer; -i also prints the headers.

$ curl -s -i "https://api.open-meteo.com/v1/forecast?latitude=28.65195&longitude=77.23149&current=temperature_2m%2Cweather_code&daily=temperature_2m_max%2Ctemperature_2m_min%2Cprecipitation_probability_max%2Cweather_code&timezone=auto&forecast_days=1"
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
X-RateLimit-Cost: 1.0
X-RateLimit-Limit: 600.0
X-RateLimit-Remaining: 599.0
X-RateLimit-Window: 60

{"latitude":28.646748,"longitude":77.2748,"generationtime_ms":0.23555755615234375,"utc_offset_seconds":19800,"timezone":"Asia/Kolkata","timezone_abbreviation":"GMT+5:30","elevation":231.0,"current_units":{"time":"iso8601","interval":"seconds","temperature_2m":"°C","weather_code":"wmo code"},"current":{"time":"2026-11-11T21:00","interval":900,"temperature_2m":22.6,"weather_code":0},"daily_units":{"time":"iso8601","temperature_2m_max":"°C","temperature_2m_min":"°C","precipitation_probability_max":"%","weather_code":"wmo code"},"daily":{"time":["2026-11-11"],"temperature_2m_max":[27.9],"temperature_2m_min":[17.6],"precipitation_probability_max":[0],"weather_code":[0]}}

200 OK means it worked. Weather code 0 is "clear sky" in the WMO codes Open-Meteo uses.

Reading JSON

JSON (JavaScript Object Notation) is a text format for data (Episode 10). The same answer, spaced out and shortened:

{
  "timezone": "Asia/Kolkata",
  "current": {
    "time": "2026-11-11T21:00",
    "temperature_2m": 22.6,
    "weather_code": 0
  },
  "daily": {
    "time": ["2026-11-11"],
    "temperature_2m_max": [27.9],
    "temperature_2m_min": [17.6],
    "precipitation_probability_max": [0]
  }
}
  • { } is an object: names with values. current is an object inside the object; in JavaScript you read data.current.temperature_2m.
  • [ ] is an array (a list). One day was asked for, so each daily array has one value: data.daily.temperature_2m_max[0] is 27.9.

Geocoding: from a city name to coordinates

The forecast needs latitude (how far north or south) and longitude (how far east or west), the two numbers that pin any place on Earth. People type names, so a second API, geocoding, turns a name into coordinates (open-meteo.com/en/docs/geocoding-api: /v1/search, parameter name, count = how many results, default 10).

$ curl -s "https://geocoding-api.open-meteo.com/v1/search?name=Delhi&count=1&language=en&format=json"
{"results":[{"id":1273294,"name":"Delhi","latitude":28.65195,"longitude":77.23149,"elevation":227.0,"feature_code":"PPLA","country_code":"IN","admin1_id":1273293,"timezone":"Asia/Kolkata","population":11034555,"country_id":1269750,"country":"India","admin1":"National Capital Territory of Delhi"}],"generationtime_ms":0.166893}

count=1 means "give me only the first match". Remember it.

fetch, promises and async/await

fetch(url) is the built-in JavaScript function that sends a request. It works in browsers and in Node.js.

Try 1: the obvious way fails

// weather.js — try 1: just call fetch and read the answer
const url = "https://api.open-meteo.com/v1/forecast?latitude=28.66&longitude=77.23&current=temperature_2m";
const response = fetch(url);
console.log(response);
console.log(response.current);

Real output (node fetch1.js):

Promise { <pending> }
undefined

Why: a request takes time to travel. JavaScript doesn't freeze while it waits, so fetch returns a promise: a value that comes later (MDN: fetch() returns "a promise that is fulfilled once the response is available"). It's a food-court buzzer: you get the buzzer now, the food later. Pending means "not yet". We read the buzzer, not the food.

Food court JavaScript
you order and get a buzzer a promise (pending)
it rings: food ready, or "sold out" the promise resolves (a value) or rejects (an error)
you wait at your table; the mall keeps running await: pause this function only

MDN: "An await expression pauses the execution of the async function and waits for the passed Promise to resolve." await only works inside a function marked async.

Try 2: async and await (real)

// weather.js — try 2: wait for the answer with await
const url = "https://api.open-meteo.com/v1/forecast?latitude=28.66&longitude=77.23&current=temperature_2m";

async function main() {
  const response = await fetch(url);
  console.log("Status:", response.status, response.ok);
  const data = await response.json();
  console.log(data.current);
  console.log(`Delhi right now: ${data.current.temperature_2m}°C`);
}

main();
Status: 200 true
{ time: '2026-11-11T15:30', interval: 900, temperature_2m: 22.6 }
Delhi right now: 22.6°C

response.json() reads the body and turns it into a JavaScript object; it takes time too, so it's awaited. The time is 15:30 because this URL has no timezone parameter, so the API answers in GMT (UTC); in India it was 21:00. Add &timezone=auto for local time.

When it breaks: fetch only fails when the network fails

A typo in a parameter (temprature_2m), with no status check (real output of node fetch3.js):

{
  reason: 'Invalid value: Cannot initialize SurfacePressureAndHeightVariable<VariableAndPreviousDay, VariableOrSpread<ForecastPressureVariable>, ForecastHeightVariable> from invalid String value temprature_2m',
  error: true
}
fetch3.js:8
  console.log(`Delhi right now: ${data.current.temperature_2m}°C`);
                                               ^

TypeError: Cannot read properties of undefined (reading 'temperature_2m')

The server answered 400 Bad Request with {"error":true,"reason":...}, but the code didn't check, read data.current (which doesn't exist in an error answer) and crashed.

MDN: "A fetch() promise only rejects when the request fails, for example, because of a badly-formed request URL or a network error. A fetch() promise does not reject if the server responds with HTTP status codes that indicate errors (404, 504, etc.)." So check response.ok (true only for status 200 to 299) and use try/catch: try runs the code; if anything throws, catch runs instead.

async function getTemp(url) {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error(`HTTP ${response.status}`);
  }
  const data = await response.json();
  return data.current.temperature_2m;
}

async function main() {
  const good = "https://api.open-meteo.com/v1/forecast?latitude=28.66&longitude=77.23&current=temperature_2m";
  const typo = "https://api.open-meteo.com/v1/forecast?latitude=28.66&longitude=77.23&current=temprature_2m";
  const offline = "https://api.open-meteoo.com/v1/forecast?latitude=28.66&longitude=77.23&current=temperature_2m";
  for (const url of [good, typo, offline]) {
    try {
      const temp = await getTemp(url);
      console.log("OK:", temp, "°C");
    } catch (err) {
      console.log("Could not get the weather:", err.message, err.cause ? `(${err.cause.code})` : "");
    }
  }
}

main();
OK: 22.6 °C
Could not get the weather: HTTP 400
Could not get the weather: fetch failed (ENOTFOUND)

ENOTFOUND: the computer couldn't find the host name api.open-meteoo.com at all; that one is the promise really rejecting.

Loading and error states

A screen that waits for the internet is always in one of four states:

Idle ──▶ Loading ──▶ Success (show the data)
                └──▶ Error   (say what to do)
  • Loading: say so, and disable the button so nobody sends ten requests.
  • Error: plain words, never a blank screen.
  • Plan for nothing found too.

One prompt: the agent builds the weather page (real run 1)

claude -p "Make a weather page for me in this folder: index.html, style.css and app.js. I type a city name, press a button, and it shows today's weather for that city: temperature, rain chance, and a short description. Plain HTML, CSS and JavaScript, no frameworks." --allowedTools Read Write Edit Glob "Bash(ls:*)"

The agent wrote the three files and chose the free Open-Meteo APIs ("no API key needed"). Its check (node --check app.js and a curl) needed approval and didn't run. Its reply: "I haven't tested it: the command to check the JavaScript and call the weather service needed approval and didn't run, so I haven't seen it work in a browser yet." So we test it.

The AI's code (first version, the important parts)

async function findCity(name) {
  const url = `${GEOCODE_URL}?name=${encodeURIComponent(name)}&count=1&language=en&format=json`;
  const res = await fetch(url);
  if (!res.ok) throw new Error(`Geocoding failed: ${res.status}`);
  const data = await res.json();
  return data.results ? data.results[0] : null;
}

async function getWeather(lat, lon) {
  const params = new URLSearchParams({
    latitude: lat,
    longitude: lon,
    current: "temperature_2m,weather_code",
    daily: "temperature_2m_max,temperature_2m_min,precipitation_probability_max,weather_code",
    timezone: "auto",
    forecast_days: "1",
  });
  const res = await fetch(`${FORECAST_URL}?${params}`);
  if (!res.ok) throw new Error(`Forecast failed: ${res.status}`);
  return res.json();
}
  • encodeURIComponent makes the city name safe inside a URL (spaces, commas, accents).
  • URLSearchParams builds name=value&name=value for you.
  • Both functions check res.ok.

The submit handler covers all four states: "Loading…" + a disabled button; "Couldn't find a city called ..."; the weather; and "Something went wrong. Please try again." in catch, with finally turning the button back on.

Testing it (real answers, 11 Nov 2026)

Typed The page showed Correct?
Delhi Delhi, National Capital Territory of Delhi, India · Clear sky · 23°C (high 28°, low 18°) · rain 0% yes
(internet off) "Something went wrong. Please try again." yes
Kochi Kochi, Kochi, Japan · Overcast · 13°C · rain 0% no
Bangalore Bangalore Town, Sindh, Pakistan · 26°C no
Dilhi (typo) Dilhi, Rajasthan, India (a village) · no warning no

The bug the AI made: the wrong city, silently

$ curl -s ".../v1/search?name=Kochi&count=5&language=en&format=json"
 1. Kochi   | Kochi    | Japan  | population 332059
 2. Kochi   | Kerala   | India  | population 633553
 3. Kōchi   | Shizuoka | Japan
 4. Kōchi   | Gunma    | Japan
 5. Kōchi   | Mie      | Japan
$ curl -s ".../v1/search?name=Bangalore&count=5&language=en&format=json"
 1. Bangalore Town | Sindh | Pakistan
$ curl -s ".../v1/search?name=Bengaluru&count=5&language=en&format=json"
 1. Bengaluru | Karnataka | India

The code asked for count=1 and took results[0]. It works perfectly, but answers a different question than the user asked, and no error message will ever show it. Only testing with the names real users type does. The real Kochi, Kerala that evening: light drizzle, 27°C, 77% chance of rain.

The fix (real run 2)

Ravi committed first, then gave the evidence:

claude -p "Bug: I live in Kerala. I typed Kochi and the page showed the weather for \"Kochi, Kochi, Japan\": 13°C, and the date there is already tomorrow. I typed Bangalore and got \"Bangalore Town, Sindh, Pakistan\". And when I mistyped Delhi as Dilhi, it showed a village in Rajasthan without any warning. The page silently takes the first match (count=1). Fix it: ask the geocoding API for up to 5 matches; if there is more than one, show them as a list (name, state, country) and let me pick one before showing the weather. Change only what's needed. I'll test it in the browser myself." --allowedTools Read Write Edit Glob

The agent edited index.html (an empty <ul id="choices">), style.css and app.js, and replied: "I've made the fix, but haven't run it. ... Dilhi depends on what the API returns. If it finds several places, you'll get the list. If it finds only one, that one is still shown straight away without a warning, because that's the single-match rule you asked for."

Re-test (real answers)

Typed The page showed
Kochi "Found 5 places matching "Kochi". Pick one:" → Kochi, Kerala, India: Light drizzle, 27°C (high 32°, low 24°), rain 77%
Bangalore only 1 match → still Bangalore Town, Sindh, Pakistan
Bengaluru Bengaluru, Karnataka, India · Overcast · 22°C
Delhi now asks: Delhi (India) or Delhi in New York, California, Louisiana, Iowa

Every fix is a trade-off. For Ravi's own app, showing the full place name and letting him pick is enough. For many users you might sort Indian results first, remember the last choice, or show "Not this place?" under the heading.

The final code (real, after the fix)

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Weather Today</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <main class="card">
    <h1>Today's Weather</h1>

    <form id="search-form">
      <input id="city-input" type="text" placeholder="Enter a city, e.g. Delhi" autocomplete="off" required>
      <button id="search-btn" type="submit">Get weather</button>
    </form>

    <p id="status" class="status" role="status"></p>

    <ul id="choices" class="choices" hidden></ul>

    <section id="result" class="result" hidden>
      <h2 id="place"></h2>
      <p id="description" class="description"></p>
      <div class="stats">
        <div class="stat">
          <span class="label">Temperature now</span>
          <span id="temp" class="value"></span>
          <span id="range" class="sub"></span>
        </div>
        <div class="stat">
          <span class="label">Chance of rain</span>
          <span id="rain" class="value"></span>
        </div>
      </div>
    </section>

    <footer>Data from <a href="https://open-meteo.com/" target="_blank" rel="noopener">Open-Meteo</a></footer>
  </main>

  <script src="app.js"></script>
</body>
</html>

app.js:

// Uses the free Open-Meteo APIs (no API key needed).
const GEOCODE_URL = "https://geocoding-api.open-meteo.com/v1/search";
const FORECAST_URL = "https://api.open-meteo.com/v1/forecast";

// WMO weather codes -> short descriptions
const WEATHER_CODES = {
  0: "Clear sky",
  1: "Mainly clear",
  2: "Partly cloudy",
  3: "Overcast",
  45: "Fog",
  48: "Freezing fog",
  51: "Light drizzle",
  53: "Drizzle",
  55: "Heavy drizzle",
  56: "Light freezing drizzle",
  57: "Freezing drizzle",
  61: "Light rain",
  63: "Rain",
  65: "Heavy rain",
  66: "Light freezing rain",
  67: "Freezing rain",
  71: "Light snow",
  73: "Snow",
  75: "Heavy snow",
  77: "Snow grains",
  80: "Light showers",
  81: "Showers",
  82: "Heavy showers",
  85: "Light snow showers",
  86: "Snow showers",
  95: "Thunderstorm",
  96: "Thunderstorm with hail",
  99: "Severe thunderstorm with hail",
};

const form = document.getElementById("search-form");
const input = document.getElementById("city-input");
const button = document.getElementById("search-btn");
const statusEl = document.getElementById("status");
const resultEl = document.getElementById("result");
const choicesEl = document.getElementById("choices");

form.addEventListener("submit", async (event) => {
  event.preventDefault();
  const city = input.value.trim();
  if (!city) return;

  setStatus("Loading…");
  resultEl.hidden = true;
  clearChoices();
  button.disabled = true;

  try {
    const places = await findCities(city);
    if (places.length === 0) {
      setStatus(`Couldn't find a city called "${city}".`, true);
      return;
    }
    if (places.length === 1) {
      await loadWeather(places[0]);
      return;
    }
    setStatus(`Found ${places.length} places matching "${city}". Pick one:`);
    showChoices(places);
  } catch (err) {
    console.error(err);
    setStatus("Something went wrong. Please try again.", true);
  } finally {
    button.disabled = false;
  }
});

async function findCities(name) {
  const url = `${GEOCODE_URL}?name=${encodeURIComponent(name)}&count=5&language=en&format=json`;
  const res = await fetch(url);
  if (!res.ok) throw new Error(`Geocoding failed: ${res.status}`);
  const data = await res.json();
  return data.results || [];
}

async function loadWeather(place) {
  setStatus("Loading…");
  const weather = await getWeather(place.latitude, place.longitude);
  showWeather(place, weather);
  setStatus("");
}

function formatPlace(place) {
  return [place.name, place.admin1, place.country].filter(Boolean).join(", ");
}

function showChoices(places) {
  for (const place of places) {
    const li = document.createElement("li");
    const choice = document.createElement("button");
    choice.type = "button";
    choice.textContent = formatPlace(place);
    choice.addEventListener("click", async () => {
      clearChoices();
      button.disabled = true;
      try {
        await loadWeather(place);
      } catch (err) {
        console.error(err);
        setStatus("Something went wrong. Please try again.", true);
      } finally {
        button.disabled = false;
      }
    });
    li.appendChild(choice);
    choicesEl.appendChild(li);
  }
  choicesEl.hidden = false;
}

function clearChoices() {
  choicesEl.replaceChildren();
  choicesEl.hidden = true;
}

async function getWeather(lat, lon) {
  const params = new URLSearchParams({
    latitude: lat,
    longitude: lon,
    current: "temperature_2m,weather_code",
    daily: "temperature_2m_max,temperature_2m_min,precipitation_probability_max,weather_code",
    timezone: "auto",
    forecast_days: "1",
  });
  const res = await fetch(`${FORECAST_URL}?${params}`);
  if (!res.ok) throw new Error(`Forecast failed: ${res.status}`);
  return res.json();
}

function showWeather(place, weather) {
  const placeName = formatPlace(place);

  const temp = Math.round(weather.current.temperature_2m);
  const max = Math.round(weather.daily.temperature_2m_max[0]);
  const min = Math.round(weather.daily.temperature_2m_min[0]);
  const rain = weather.daily.precipitation_probability_max[0];
  const code = weather.daily.weather_code[0];

  document.getElementById("place").textContent = placeName;
  document.getElementById("description").textContent =
    WEATHER_CODES[code] || "Unknown conditions";
  document.getElementById("temp").textContent = `${temp}°C`;
  document.getElementById("range").textContent = `High ${max}° / Low ${min}°`;
  document.getElementById("rain").textContent = rain == null ? "–" : `${rain}%`;

  resultEl.hidden = false;
}

function setStatus(message, isError = false) {
  statusEl.textContent = message;
  statusEl.classList.toggle("error", isError);
}

Rate limits and API keys

A rate limit is the most requests you may send in a period of time. Open-Meteo's real headers: X-RateLimit-Limit: 600.0, X-RateLimit-Window: 60 (600 per 60 seconds), X-RateLimit-Remaining: 599.0. Its terms: under 10,000 calls a day, 5,000 an hour and 600 a minute for free non-commercial use. A bug that calls the API in a loop can use that up quickly.

Many APIs need an API key: a long secret string that says which account is asking; it's how they count, limit and often bill your requests. A real call to OpenWeatherMap with a placeholder instead of a key:

$ curl -s -i "https://api.openweathermap.org/data/2.5/weather?q=Delhi&appid=YOUR_API_KEY_HERE"
HTTP/1.1 401 Unauthorized
Content-Type: application/json; charset=utf-8

{"cod":401, "message": "Invalid API key. Please see https://openweathermap.org/faq#error401 for more info."}

Treat a real key like your ATM PIN.

.env files, environment variables and .gitignore (real)

  • Environment variables: settings a program reads from outside its code.
  • .env: a file of NAME=value lines holding them, kept out of the code.
  • .gitignore: a list of files Git must never save.
$ printf 'OPENWEATHER_API_KEY=your_key_here\n' > .env
$ git status --short
?? .env
$ echo .env >> .gitignore
$ git status --short
?? .gitignore
$ git add . && git commit -m "Ignore .env"
$ git check-ignore -v .env
.gitignore:1:.env   .env

Add .env to .gitignore before the first commit. If a key was ever committed or pushed, treat it as leaked: create a new key in the provider's dashboard and delete the old one.

The catch: a browser page can't keep a secret

Everything in app.js is downloaded by every visitor; anyone can read it with DevTools (the browser's developer tools, Sources or Network tab), even if the key came from a .env file at build time. Keyless APIs like Open-Meteo are fine to call from the browser. APIs with a secret key must be called from your own server, which keeps the key and sends back only the result: the topic of Episode 14.

$ git log --oneline
34c4f39 Ignore .env
59ea872 Let me pick the place when the name matches several (AI)
7acf73a Weather page (AI)

Common mistakes (real)

Mistake What you see Why Fix
const r = fetch(url); r.current Promise { <pending> }, undefined the answer isn't there yet await fetch(...) inside an async function
no response.ok check TypeError: Cannot read properties of undefined (reading 'temperature_2m') fetch resolves even on 400/404 if (!response.ok) throw new Error(...)
a typo in a query parameter 400 + {"error":true,"reason":"Invalid value: ..."} the API only knows its own names copy names from the API docs
wrong host name / no internet TypeError: fetch failed (ENOTFOUND) the request never arrived try/catch and a friendly message
count=1, results[0] Kochi → Kochi, Japan, with no error the first match is taken silently show the full place name; let users pick
no timezone parameter time: '2026-11-11T15:30' at 21:00 in India the API answers in GMT timezone=auto
a real key in code / committed .env a leaked key; someone else's 401 is your bill code is shared .env + .gitignore; keyed APIs via a server

Mini project

Ask an AI to add tomorrow's forecast to this page (forecast_days=2, read index [1] of each daily array) and a "Not this place?" link under the heading that shows the other matches again. Then test: Kochi, Bangalore, Bengaluru, Hyderabad, Salem, a typo, an empty box, and the internet switched off (DevTools → Network → Offline).

What a good outcome looks like

Tomorrow's high, low and rain chance appear under today's, read from daily.*[1]. Hyderabad and Salem show a list (Hyderabad also matches places in Pakistan; Salem also matches US towns). Bangalore still finds only Bangalore Town, Pakistan, but the heading makes it obvious and "Not this place?" lets you search again; Bengaluru works. An empty box sends no request. Offline shows the friendly error, and the button works again afterwards.

Practice questions

  1. What is an API, in one sentence?
Answer

A set of rules for how one program asks another program for something (what you may ask, how to ask, what comes back).

  1. In https://api.open-meteo.com/v1/forecast?latitude=28.65&longitude=77.23, which part is the endpoint and which are query parameters?
Answer

The endpoint is /v1/forecast on the server api.open-meteo.com; latitude=28.65 and longitude=77.23 are query parameters.

  1. Why does console.log(fetch(url)) print Promise { <pending> }?
Answer

fetch returns a promise immediately; the response arrives later. Use await (inside an async function) to get it.

  1. The server answers 404. Does await fetch(url) throw?
Answer

No. fetch only rejects on network failures. The promise resolves and response.ok is false; you must check it.

  1. Why did the first version show the weather for Japan when Ravi typed Kochi?
Answer

It asked the geocoding API for count=1 and used results[0]; for "Kochi" the first result is Kochi, Japan.

  1. Where should a secret API key live in a project, and why isn't that enough for a browser-only app?
Answer

In a .env file listed in .gitignore. In a browser-only app the code (and any key built into it) is downloaded by every visitor, so keyed APIs must be called from a server.

Quiz

const response = await fetch("https://api.example.com/nothing-here");
// the server answers: 404 Not Found
console.log(response.ok);

What does it print? A) fetch throws an error B) true C) false D) undefined

Answer

C) false. A 404 is still an answer, so the promise resolves; response.ok is true only for 200-299.

Interview questions

  1. What happens, step by step, when a page calls fetch and then response.json()?
  2. What is a promise? What do pending, resolved and rejected mean?
  3. Why doesn't fetch reject on a 500, and how do you handle it?
  4. How would you design loading, empty and error states for a search box?
  5. How do you keep an API key secret in a front-end app?
  6. What is a rate limit, and how would you avoid hitting one?

Glossary

Term Meaning (plain words) Example
API a set of rules for how one program asks another for something Open-Meteo's forecast API
Public API an API anyone may use (sometimes free, sometimes with a key) Open-Meteo
Server a computer program that waits for requests and answers them api.open-meteo.com
Endpoint one address on an API for one kind of question /v1/forecast
URL the full address of something on the web https://api.open-meteo.com/v1/forecast?...
Query parameter a name=value pair after ? in a URL, joined with & latitude=28.65
HTTP the rules browsers and servers use to ask and answer HTTP/1.1 200 OK
HTTP request a message asking a server for something GET /v1/forecast?...
GET the request method meaning "give me this" opening a URL
Response what the server sends back: status, headers, body 200 OK + JSON
Status code a number saying how it went 200, 400, 401, 404
Header a label on a request or response Content-Type: application/json
JSON a text format for data, made of objects and arrays {"temperature_2m":22.6}
Object (JSON) { } holding names with values "current": {...}
Array [ ], a list of values [27.9]
curl a command-line tool that sends HTTP requests curl -s -i URL
Latitude / longitude the two numbers that pin a place: north–south, east–west 28.65, 77.23 (Delhi)
Geocoding turning a place name into coordinates Delhi → 28.65, 77.23
fetch the built-in JavaScript function that sends a request fetch(url)
Promise a value that will be ready later Promise { <pending> }
Pending / resolved / rejected not ready yet / got a value / failed a network error rejects
async function a function that can wait for promises with await async function main()
await pause this async function until the promise settles await fetch(url)
response.json() read the body and turn JSON into a JavaScript object await response.json()
response.ok true when the status is 200–299 false for 404
try / catch run code; if something throws, run the catch block show "Something went wrong"
throw raise an error on purpose throw new Error("HTTP 400")
TypeError a JavaScript error for using a value the wrong way reading a property of undefined
ENOTFOUND "this host name doesn't exist / can't be found" api.open-meteoo.com
Loading state what the screen shows while it waits "Loading…"
Error state what the screen shows when something fails "Please try again."
encodeURIComponent makes text safe to put inside a URL New Delhi → New%20Delhi
URLSearchParams builds name=value&... for you new URLSearchParams({...})
Time zone the local clock of a place Asia/Kolkata (GMT+5:30)
Rate limit the most requests allowed in a period of time 600 per minute
API key a secret string that says which account is asking appid=...
401 Unauthorized the server didn't accept who you are invalid API key
Environment variable a setting a program reads from outside its code OPENWEATHER_API_KEY
.env file a file of NAME=value secrets and settings OPENWEATHER_API_KEY=your_key_here
.gitignore a list of files Git must never save .env
DevTools the browser's built-in developer tools Network tab
Edge case an unusual input that breaks naive code a city name with two matches

Summary

Our apps only knew what we typed; live data like weather lives on someone else's server, and an API is the set of rules for asking it. We asked Open-Meteo with a URL and query parameters (an HTTP GET request) and got JSON back; geocoding turned a city name into latitude and longitude. In JavaScript, fetch returns a promise (Promise { <pending> }), so we await it inside an async function; and because fetch doesn't fail on error codes, we check response.ok and use try/catch. The agent built a clean page with loading and error states, but never tested it, and it silently took the first match: Kochi went to Japan (0% rain) instead of Kerala (77%). One precise prompt fixed it, and re-testing showed what was left (Bangalore). Finally: rate limits, API keys, .env + .gitignore, and why a browser page can't keep a secret, which is why next we build a backend.