TalentJR

🟨 JavaScript tutorial for beginners · Class 9 · Lesson 4 of 18 · Free

API Calls – Get Data from a Server with fetch() in JavaScript

⏱ About 40 minutes · ▶ run real JavaScript here — nothing to install · no sign-in

In this lesson you will

  • Explain what an API, a request and a response are
  • Fetch JSON data with fetch() and async/await, and check response.ok
  • Send data to a server with a POST request and show API data on a page

A weather app on a phone does not know today's weather by itself. It asks a server far away, and the server sends back the answer in a second. In this lesson your own code will ask a real server for weather, students' marks and to-dos — and show the answers on a page.

What is an API and how does fetch() work in JavaScript?

An API (Application Programming Interface) is a menu a server offers to programs. You send a request to a web address (a URL), and the server sends back a response with data.

In this lesson we use the TalentJR practice API. Its data is made up for learning, so the answers are always the same — perfect for practice.

`fetch(url)` sends the request and returns a Promise (Lesson 3). The response arrives first, then you read its body with `response.json()`, which is also a Promise.

🟨 JavaScript — you can edit this code
Console output
Code is like humour: when you have to explain it, it is bad.
Topic: coding

💡 Try it: change /quotes/2 to /quotes/1 and run again.

How do I use fetch with async and await in JavaScript?

The same thing reads more easily with `await`. First await the response, then await the JSON inside it.

The weather answer is an object with properties like `temp_c` and `condition`, plus a `forecast` array of three days. You read it with dots, as in Lesson 1.

The `?city=Pune` part of the URL is a query parameter. It tells the server which city you want.

🎬 How JavaScript thinks — step 1 of 12JavaScript is about to run line 1
▶const API = "https://api.talentjr.in/api/v1/practice";
2
3const response = await fetch(`${API}/weather?city=Pune`);
4const weather = await response.json();
5
6console.log(`${weather.city}: ${weather.temp_c}°C, ${weather.condition}`);
7console.log(`Humidity ${weather.humidity}%, wind ${weather.wind_kmh} km/h`);
8for (const day of weather.forecast) {
9 console.log(`${day.day}: ${day.low}–${day.high}°C ${day.condition}`);
10}
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🟨 JavaScript — you can edit this code
Console output
Pune: 24°C, Sunny
Humidity 40%, wind 12 km/h
Mon: 17–29°C Sunny
Tue: 18–30°C Cloudy
Wed: 17–28°C Sunny

💡 Try it: change Pune to Shimla, Chennai or Jaipur.

What is JSON and how do I read it in JavaScript?

Servers send data as plain text in a format called JSON (JavaScript Object Notation). It looks like a JavaScript object, but every key must be in double quotes.

`JSON.parse(text)` turns JSON text into a real object. `JSON.stringify(object)` does the opposite. `response.json()` simply calls the parse step for you.

Why text? Because text can travel over the internet and be read by any language — Python, Java or JavaScript.

🎬 How JavaScript thinks — step 1 of 8JavaScript is about to run line 1
▶const text = '{"name": "Meera", "cls": 9, "marks": [81, 95]}';
2console.log(typeof text);
3
4const student = JSON.parse(text);
5console.log(typeof student);
6console.log(student.name, student.marks[1]);
7
8const back = JSON.stringify({ city: "Pune", temp: 24 });
9console.log(back);
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🟨 JavaScript — you can edit this code
Console output
string
object
Meera 95
{"city":"Pune","temp":24}

💡 Single quotes outside let us use double quotes inside the JSON text.

How do I check if a fetch request worked (status and response.ok)?

Every response has a status code. 200 means OK, 201 means created, 404 means not found, and 500 means the server had a problem.

Surprise: `fetch` does NOT fail on 404 or 500. It only fails if the network is down. So you must check `response.ok`, which is true only for codes 200–299.

Here we ask for one good city, one city the API does not have, and an address that breaks on purpose.

🟨 JavaScript — you can edit this code
Console output
✅ 200
❌ 404: City not found
❌ 500: The server had a problem (this one breaks on purpose, for practice).

💡 Lesson 5 shows how to turn a bad status into a proper error with throw.

How do I send data to a server with a POST request?

So far we only asked for data (a GET request). To send data, use a POST request. Pass a second argument to `fetch` with the method, headers and body.

The body must be text, so turn your object into JSON with `JSON.stringify`. The header `Content-Type: application/json` tells the server what kind of text it is.

The practice API sends your new to-do back with status 201, but it does not really save it.

🟨 JavaScript — you can edit this code
Console output
201
{ id: 4, title: "Revise Science chapter 3", done: false, saved: false, note: "Practice API: the new to-do is sent back but not saved." }

💡 Try it: send an empty title "" and look at the status and the error.

How do I show API data on a web page with JavaScript?

Now join fetch with the DOM from Class 8. Pick a city, click the button, and the page shows the weather.

While waiting, show "Loading…" so the user knows something is happening. When the data arrives, replace it with the result.

The code also loads Pune once at the start, so you see a result straight away.

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
Pune: 24°C, Sunny

🤔 Predict the output

Think like JavaScript: read the code and choose what it prints. You get the reason straight away.

Question 1. Goa is not in the practice API. What does this print?

const API = "https://api.talentjr.in/api/v1/practice";
const response = await fetch(`${API}/weather?city=Goa`);
console.log(response.ok, response.status);

Question 2. What does this print?

console.log(JSON.stringify({ name: "Asha", marks: 92 }));

Question 3. What does this print?

const data = JSON.parse('{"city": "Pune", "temp_c": 24}');
console.log(data.temp);

🧩 Your challenge

Fetch all students from the practice API (`${API}/students`). For each student, print the name and the total of maths + science + english. Then use reduce (Lesson 2) to find the topper and print them. Expected output: Asha: 259 Rohan: 226 Meera: 266 Kabir: 191 Zoya: 284 Topper: Zoya with 284

Expected output in the console:
Asha: 259
Rohan: 226
Meera: 266
Kabir: 191
Zoya: 284
Topper: Zoya with 284
🟨 JavaScript — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

const API = "https://api.talentjr.in/api/v1/practice";
const response = await fetch(`${API}/weather?city=Mumbai`);
const weather = response.json();
console.log(weather.forecast.length);

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

✅ Right

const API = "https://api.talentjr.in/api/v1/practice";
const response = await fetch(`${API}/weather?city=Mumbai`);
const weather = await response.json();
console.log(weather.forecast.length);

response.json() also returns a Promise. Without await, weather is the Promise, which has no forecast.

❌ Wrong

const API = "https://api.talentjr.in/api/v1/practice";
const response = await fetch(`${API}/students/9`);
const student = await response.json();
console.log(`Name: ${student.name}`);

No error, but it prints "Name: undefined" — student 9 does not exist, and the reply is { error: "Student not found" }.

✅ Right

const API = "https://api.talentjr.in/api/v1/practice";
const response = await fetch(`${API}/students/9`);
const student = await response.json();
if (response.ok) {
  console.log(`Name: ${student.name}`);
} else {
  console.log(`Error ${response.status}: ${student.error}`);
}

fetch does not fail on a 404. Check response.ok before using the data.

❌ Wrong

const API = "https://api.talentjr.in/api/v1/practice";
const response = await fetch(`${API}/todos`, {
  method: "POST",
  body: { title: "Buy rakhi" }
});
console.log(response.status);

No error, but it prints 422 instead of 201 — the object was sent as the text "[object Object]", which the server cannot understand.

✅ Right

const API = "https://api.talentjr.in/api/v1/practice";
const response = await fetch(`${API}/todos`, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ title: "Buy rakhi" })
});
console.log(response.status);

The body must be JSON text, not an object, and the server needs the Content-Type header to read it.

📌 Remember

  • An API lets your program ask a server for data: you send a request to a URL and get a response.
  • fetch(url) returns a Promise; await the response, then await response.json().
  • JSON is text that looks like an object; JSON.parse reads it, JSON.stringify writes it.
  • fetch does not fail on 404 or 500 — always check response.ok or response.status.
  • To send data, use method: "POST", a Content-Type header and a JSON.stringify body.

Finished the quiz and the challenge?

Questions students ask

What is an API in simple words?

An API is like a waiter in a restaurant. You (the program) give an order (a request), the waiter takes it to the kitchen (the server), and brings back your food (the response). You do not need to know how the kitchen works.

Why do I need two awaits with fetch?

The first await waits for the response to start arriving, with its status and headers. The body may still be loading, so response.json() is a second Promise that waits for the whole body and parses it.

Why does fetch fail with a CORS error on some websites?

Browsers only let a page read data from another website if that website allows it. This rule is called CORS. The TalentJR practice API allows it, but many other sites do not, or they need a secret API key.

Is JSON the same as a JavaScript object?

No. JSON is text in a strict format: keys in double quotes, no functions, no comments. A JavaScript object lives in memory. JSON.parse and JSON.stringify convert between them.