Fetching real data
You'll learn to ask a server for data with fetch, turn the reply into a JavaScript object, and find the value you need.
fetch is how you get it.Watch & read
Start with the required ones. The others are there when you need them.
See it step by step
From a request to a number on the screen.
Explanation
You want your weather page to show the real temperature in Dhaka right now. Your code doesn't know it. A server somewhere does. You need to ask it.
A server that answers questions from code, not from people, is called an API. You send a request to its address (a URL), and it sends back a response. It's like sending an SMS to a number that replies with your balance.
In JavaScript you ask with fetch. It gives back a promise, so you await it:
const url = "https://api.open-meteo.com/v1/forecast?latitude=23.81&longitude=90.41¤t=temperature_2m";const response = await fetch(url);const data = await response.json();console.log(data.current.temperature_2m); // 31.3
There are two waits. The first await waits for the response to start arriving. The body is still
plain text in a format called JSON. It looks just like a JavaScript object. The second await,
on response.json(), waits for the whole body and turns it into a real object you can use.
To find the value you need, open the URL in your browser and read the JSON. Here it looks like this:
{ "latitude": 23.8, "current": { "time": "2026-10-19T10:45", "temperature_2m": 31.3 } }
The temperature is inside current, so the path is data.current.temperature_2m.
People often forget the second await. Then data is a promise, and data.current is undefined.
The other common mistake is guessing the path, like data.temperature. Don't guess. Look at the real
JSON first, then follow it one dot at a time.
When you read fetch code, find three things: the URL (who you ask), the two awaits, and the path into
the data. After that it's ordinary objects and arrays, and you already know map for lists.
Code tour
Click a line number with a ring to read the note for that line.
Practice
Short drills. Take your time and read the code before you answer.
1async function showTemp() {2 const response = await fetch(weatherUrl);3 const data = response.json();4 console.log(data.current);5}6showTemp();7// The server sends: { "current": { "temperature_2m": 31.3 } }
readTemp gets the object from await response.json(). Its shape is in the comment. It should return the temperature number. Fix it so both checks pass.cityNames returns the whole place objects. Change it so it returns only the names, like ["Dhaka", "Sylhet"].Quick check
3 questions. Each one explains itself after you answer.
- 1 / 3What does
await response.json()do? - 2 / 3The JSON is
{ "city": "Dhaka", "current": { "temp": 31 } }. How do you get31? - 3 / 3
const data = response.json();(noawait). What isdata?
Explain it back
How confident are you with Fetching real data?
Done
fetch call, say what each await waits for, and pick the right value out of the JSON.