{module 6}
Call a public API with fetch
How programs talk to each other20 min read
What you will be able to do
- Request data from a public API with
fetch, and wait for the answer withasyncandawait. - Check that the answer is a success with
response.ok, and read its JSON withresponse.json(). - Put values from the answer on a page, with the credit the API's licence asks for.
Why it matters
Valparaíso Mural Tours runs walking tours of the painted streets on the hills of Valparaíso, Chile. The hills are windy, and the weather by the sea is often different from the weather at the top. Every morning, Camila Rojas, who runs the tours, answers the same messages: "Is it cold up there? Do I need a jacket?"
She checks a weather site and replies to each person by hand. On a busy morning that takes an hour, and some people get no answer before their tour starts.
A page can ask a weather service itself, each time a visitor opens it, and show the temperature and the wind right now. In this lesson you build that page. It is your first program that talks to another program.
The idea
An API
In lesson 1 you opened an address that answered with JSON instead of a page. That server is an API, short for Application Programming Interface: a server whose answers are made for programs, not for people. Its documentation says which addresses it understands and what each answer contains.
This module uses the Open-Meteo weather API. It is free, it needs no account and no key, and it allows any page to call it. Its documentation lists the values you can ask for in the query. This lesson asks for two: temperature_2m (the air temperature 2 metres above the ground) and wind_speed_10m (the wind 10 metres up). timezone=auto asks for times in the local time of the place.
Someone else's data, someone else's rules
An API has terms of use, and you read them before you build. Open-Meteo's terms say three things that matter here:
- The free service is for non-commercial use, such as learning, personal pages and projects without advertising. A business that uses it in its own product pays for a plan.
- It allows up to 10,000 requests a day.
- The data comes under a licence that asks for credit. Next to the data, the page must show a link: "Weather data by Open-Meteo.com".
Your pages in this course are practice pages, so the free service fits. Every one of them carries the credit link.
A request that takes time
fetch is a function that sends a request from your script, the way the browser sends one when you type an address. Its first value is the address.
An answer takes time to arrive: a fraction of a second on a good connection, several seconds on a weak one. JavaScript does not stop and wait. fetch returns straight away, and what it returns is a promise: an object that stands for an answer that has not arrived yet. Later the promise ends in one of two ways. It is fulfilled with the response, or it is rejected with an error when no answer came at all. Lesson 4 is about the second way.
async and await
async function showWeather() {
const response = await fetch(address);await pauses the function on that line until the promise ends, then gives you what it was fulfilled with. Here, that is the response.
Only this function pauses. The rest of the script goes on, and the page stays usable. That is why await is allowed only inside a function marked async. The word tells the browser that this function may pause.
response.ok and response.json()
A response is an object. Two of its parts matter today:
response.okistruewhen the status code is from 200 to 299, andfalseotherwise.response.statusis the status code itself, such as200or500.
A server that answers 500 has still answered, so fetch gives you the response as usual. You must check response.ok yourself:
if (!response.ok) {
statusLine.textContent = `The weather service answered ${response.status}. Try again later.`;
return;
}! means "not", so the test reads "if the response is not ok". return with no value stops the function there.
When the answer is a success, response.json() reads its content and parses the JSON, as JSON.parse did in lesson 2. Reading takes time too, so it also returns a promise and needs its own await:
const weather = await response.json();Worked example
Make a folder called hill-weather. Create index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Weather on the hills, Valparaíso Mural Tours</title>
<script src="weather.js" defer></script>
</head>
<body>
<main>
<h1>Valparaíso Mural Tours</h1>
<h2>Weather on the hills now</h2>
<p id="status">Loading the weather</p>
<p id="temperature"></p>
<p id="wind"></p>
<p><a href="https://open-meteo.com/">Weather data by Open-Meteo.com</a></p>
</main>
</body>
</html>Then weather.js in the same folder:
const address =
"https://api.open-meteo.com/v1/forecast?latitude=-33.05&longitude=-71.62¤t=temperature_2m,wind_speed_10m&timezone=auto";
const statusLine = document.querySelector("#status");
const temperature = document.querySelector("#temperature");
const wind = document.querySelector("#wind");
async function showWeather() {
const response = await fetch(address);
if (!response.ok) {
statusLine.textContent = `The weather service answered ${response.status}. Try again later.`;
return;
}
const weather = await response.json();
console.log("3. The answer has arrived");
temperature.textContent = `Temperature: ${weather.current.temperature_2m} °C`;
wind.textContent = `Wind: ${weather.current.wind_speed_10m} km/h`;
statusLine.textContent = `Measured at ${weather.current.time}, local time`;
}
console.log("1. Asking for the weather");
showWeather();
console.log("2. The rest of the script goes on");Save both files, open index.html from the folder, and open the Console. This is what the page showed when this lesson was written. Your numbers and time will be today's:
Valparaíso Mural Tours
Weather on the hills now
Measured at 2026-11-15T14:30, local time
Temperature: 20 °C
Wind: 19.4 km/h
Weather data by Open-Meteo.comThe JSON that arrived contained this part, among others: "current":{"time":"2026-11-15T14:30","interval":900,"temperature_2m":20.0,"wind_speed_10m":19.4}. Lines 16 to 18 read three values from it, as in lesson 2.
The Console shows the order in which things happened:
1. Asking for the weather
2. The rest of the script goes on
3. The answer has arrivedLine 22 called showWeather. The function ran as far as the await on line 9 and paused. The script went on to line 23. The function finished later, when the answer had arrived.
Lines 10 to 13 handle a server that refuses. When the weather service answered 500 instead, the page showed this, and the Console showed the failed request:
Valparaíso Mural Tours
Weather on the hills now
The weather service answered 500. Try again later.
Weather data by Open-Meteo.com
page error: Failed to load resource: the server responded with a status of 500 (Internal Server Error)Common mistakes
Forgetting await before response.json()
In no-await.js, line 14 reads const weather = response.json();. The page stays on "Loading the weather", and the Console shows:
page error: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'temperature_2m')Without await, weather is the promise, not the data. A promise has no current, so weather.current is undefined, and nothing can be read from undefined. When a value from fetch does not behave like data, look for a missing await.
Forgetting async
In no-async.js, the function starts with function showWeather(), without async:
page error: Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modulesA SyntaxError means the browser could not read the script at all, so none of it ran. The message says exactly what to add. You can ignore "modules": pages in this course do not use them.
Skipping the check
In no-ok.js, the four lines that test response.ok are gone. When the server answered 500 with no content:
page error: Failed to load resource: the server responded with a status of 500 (Internal Server Error)
page error: Uncaught (in promise) SyntaxError: [...]Unexpected end of JSON inputRead the first message first: the server answered 500. The code went on and tried to read empty content as JSON, which caused the second message. Some versions of the browser put more words at its start. It is only a result of the first. The visitor sees "Loading the weather" for ever. Keep the check.
Think it through
Baraka, a learner, wants the page to show the wind in a sentence a visitor understands: "Windy on the hills, bring a jacket" when the wind is 20 km/h or more, and "Calm on the hills" when it is less.
Understand. In: the wind speed from the answer, a number. Out: one of two sentences on the page.
Break down. Read the number. Decide which sentence. Put it on the page.
Plan. After line 17, store weather.current.wind_speed_10m in a const. Use if and else with >=, as in module 4, and write the sentence into a new paragraph with the id advice.
Build. Baraka adds <p id="advice"></p> to the HTML and the decision to the script. He reloads and sees "Calm on the hills", with a wind of 19.4.
Test. He cannot change the weather, so he tests the rule with a value he chooses. For a moment he writes const windKmh = 25; and sees the jacket sentence. Then the odd case, exactly 20, which also gives the jacket sentence because the test is >=. He puts the real value back.
Reflect. Live data is hard to test, because you cannot choose it. Putting a known value in for a moment let him test both sides of the rule.
At work
When you present your work, explain one decision you made and why, in a sentence or two. It shows the client that choices were made on purpose, and it gives them a chance to disagree early.
Mateo, who built Camila's page, ended his message with this:
One decision you should know about: I used Open-Meteo for the weather. It needs no account and no password, and it answers any page. Its free service is for learning and other non-commercial use, so this version is a practice page. Before it goes on your booking site, you would need its paid plan or another source, and I can compare the two for you.
He gave the choice, the reason and its consequence for Camila, and the question she needs to decide. He did not list every other service he looked at.
Your tasks
Task 1: Build the page
Build the worked example and open it with the Console open.
You are done when the page shows today's temperature and wind in Valparaíso, and the Console shows the three lines in the order 1, 2, 3.
Task 2: Read the request in the Network panel
With the page open, open the Network panel and reload. Click the row for forecast. In its response headers, find access-control-allow-origin. This header is how a server tells the browser that pages from other places may read its answers, and its value * means any page. Without it, the browser would refuse to give the answer to your script.
You are done when you have written down the status code of the request and the value of that header.
Task 3: Your own city
Change the address so that it asks for the weather where you live. To find its latitude and longitude, open the Open-Meteo documentation linked below. At the top, under "Location and Time", click Search, type your town and choose it. The Latitude and Longitude boxes fill in with its numbers. Change the heading of your page to match.
You are done when the page shows the weather for your own town, and the time is your local time.
Task 4: One more value
Open the Open-Meteo documentation linked below and find the name of the value for the humidity of the air. Add it to the query, and show it on the page with its unit.
You are done when the page shows the humidity as a percentage, and the number matches the one in the Response tab of the Network panel.
Recap
- An API is a server whose answers are made for programs. Read its documentation and its terms before you build, and give the credit its licence asks for.
fetchreturns a promise. Inside anasyncfunction,awaitpauses that function until the answer arrives.- A status code such as 500 is still an answer. Check
response.okbefore you read the content. response.json()also takes time, so it needs its ownawait.
Go deeper
- MDN: Using the Fetch API shows requests and responses, with the same
response.okcheck. - MDN: async function is the reference page for
asyncandawait. - Open-Meteo: Weather Forecast API lists every value you can ask for, with a form that builds the address.
- Open-Meteo: Terms of use says what the free service may be used for.
- Open-Meteo: Licence explains the credit a page must show.