← Level 5 – Inventor

Lesson 2 of 8 ⏱ 30 minutes Premium

Your first fetch

Call an API directly from JavaScript and print the response on your page.

Show me: fetch – ordering with code

In the last lesson, you opened an API in your browser by hand. Now your JavaScript will do the same thing – with the fetch command:

const adresa = 'https://api.open-meteo.com/v1/forecast?latitude=49.19&longitude=16.61&current_weather=true';

const odpoved = await fetch(adresa);
const data = await odpoved.json();

console.log(data.current_weather.temperature);

What’s happening here, line by line:

  1. fetch(adresa) – send the request (the waiter heads to the kitchen).
  2. awaitwait for it to come back. The internet takes a moment!
  3. odpoved.json() – convert the response into a JavaScript object.
  4. Then you work with the data like any regular object: dot, dot, done.
⚠️

await only works inside a function marked async, or in a <script type="module">. If your browser shows the error “await is only valid in async functions”, wrap your code like this:

async function nacti() {
  // fetch and await go here
}
nacti();

The console is for programmers – a visitor wants to see the data on the page:

<p id="teplota">Loading…</p>

<script type="module">
  const odpoved = await fetch('https://api.open-meteo.com/v1/forecast?latitude=49.19&longitude=16.61&current_weather=true');
  const data = await odpoved.json();

  document.querySelector('#teplota').textContent =
    `Right now it's ${data.current_weather.temperature} °C`;
</script>

Familiar stuff from Magician (querySelector, textContent) plus the new fetch. Nothing more.

Your turn 💪

  1. Add a paragraph with id="teplota" and the script above to your website.
  2. Change the coordinates to your own city.
  3. Add the wind speed to the display too (data.current_weather.windspeed).
  4. Bonus: when the temperature is below 0, add ”🥶 Bundle up!” to the text.

Check: The real current temperature appears on your page after it loads. If you turn off Wi-Fi and refresh the page, it stays on “Loading…” – proof that the data really comes from the internet.

What to take away from this lesson