TalentJR

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

Building an API Client – Talk to a REST API with JavaScript

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

In this lesson you will

  • Send GET and POST requests to a REST API with fetch
  • Check status codes and turn server errors into clear messages
  • Build one reusable client function and use it on a live page

A railway enquiry counter answers questions: you ask "Is train 12127 on time?" and the clerk replies. An API is a counter like that for programs. Today you write the program that asks the questions — an API client — and you make it polite, careful and reusable.

What is an API client in JavaScript?

An API is a web address that sends back data (usually JSON) instead of a web page. An API client is your code that sends a request and uses the response.

In this lesson we use the TalentJR practice API. All its data is made up, just for practice, and it allows calls from any page.

Every request has a method (GET = "give me"), a URL, and comes back with a status code and a body. You met `fetch` in Lesson 4 and `await` in Lesson 13.

🟨 JavaScript — you can edit this code
Console output
Status: 200
OK? true
{ id: 2, text: "Code is like humour: when you have to explain it, it is bad.", topic: "coding" }
Quote: Code is like humour: when you have to explain it, it is bad.

💡 Try it: change /quotes/2 to /quotes or /students and see what comes back.

How do I add query parameters to a URL in JavaScript?

The part after `?` in a URL is the query string: `?city=Pune&days=3`. It is how you tell the API what you want.

Typing it by hand breaks when a value has a space or `&` in it. `URLSearchParams` builds it safely for you and turns special characters into URL-safe codes.

Watch the trace: the object becomes a neat string, and the space in "New Delhi" becomes `+`.

🎬 How JavaScript thinks — step 1 of 17JavaScript is about to run line 1
▶const API = "https://api.talentjr.in/api/v1/practice";
2
3function buildUrl(path, options) {
4 const params = new URLSearchParams(options);
5 const query = params.toString();
6 return query ? `${API}${path}?${query}` : API + path;
7}
8
9const url1 = buildUrl("/weather", { city: "Pune" });
10const url2 = buildUrl("/weather", { city: "New Delhi", units: "C" });
11const url3 = buildUrl("/students", {});
12console.log(url1);
13console.log(url2);
14console.log(url3);
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🟨 JavaScript — you can edit this code
Console output
https://api.talentjr.in/api/v1/practice/weather?city=Pune
https://api.talentjr.in/api/v1/practice/weather?city=New+Delhi&units=C
https://api.talentjr.in/api/v1/practice/students

💡 Try it: add { class: 8 } as the options for /students.

How do I check if a fetch request worked?

Status codes tell you what happened: 200 OK, 201 Created, 400 Bad request, 404 Not found, 500 Server error. `res.ok` is true only for codes 200–299.

Big surprise for beginners: `fetch` does NOT throw an error for 404 or 500. It only throws when there is no network at all. So a good client always checks `res.ok`.

Our practice API also sends a JSON body with an `error` message when something goes wrong. Show that message to the user.

🟨 JavaScript — you can edit this code
Console output
Mumbai: 31°C, Humid
Goa: error 404 – City not found

💡 Try it: add "Shimla" and "Ooty" to the list.

How do I build a reusable API client function in JavaScript?

Writing fetch + check + json again and again is boring and easy to get wrong. Put it in ONE function, `apiGet(path)`, and use it everywhere.

When the server says no, `apiGet` throws an Error with the server's message. The caller catches it with try/catch (Lesson 5), so bad news never crashes the app.

This is what real API clients do: one careful function, many small easy calls.

🎬 How JavaScript thinks — step 1 of 15JavaScript is about to run line 1
▶const API = "https://api.talentjr.in/api/v1/practice";
2
3async function apiGet(path) {
4 const res = await fetch(API + path);
5 const data = await res.json();
6 if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
7 return data;
8}
9
10try {
11 const meera = await apiGet("/students/3");
12 console.log(meera.name, "science:", meera.marks.science);
13 const ghost = await apiGet("/students/9");
14 console.log(ghost.name);
15} catch (err) {
16 console.log("Could not load:", err.message);
17}
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🟨 JavaScript — you can edit this code
Console output
Meera science: 95
Could not load: Student not found

💡 The line console.log(ghost.name) never runs — the throw jumps straight to catch.

How do I send data to an API with POST?

GET asks for data. POST sends new data, like adding a to-do. You give fetch a second argument with `method`, `headers` and `body`.

The body must be a string, so use `JSON.stringify` (Lesson 9). The header `Content-Type: application/json` tells the server "this string is JSON".

A new item usually comes back with status 201 (Created). Our practice API sends the new to-do back but does not really save it.

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

💡 Try it: remove the headers line and run again — the server no longer understands the body.

How do I show API data on a web page?

Now join the client to the page. The user picks a student id, we show "Loading…", call `apiGet`, and fill a card — or show the error in red.

Disable the button while loading, so an impatient double-click does not send two requests.

Pick an id and click. Try 9 to see the error path.

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
Showing Asha

💡 Try it: also show the English mark in the card.

🤔 Predict the output

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

Question 1. What does this print?

const params = new URLSearchParams({ city: "New Delhi", days: 3 });
console.log(params.toString());

Question 2. A fake response with status 404 (the same kind of object fetch gives you). What does this print?

const res = new Response("{}", { status: 404 });
console.log(res.ok, res.status);

Question 3. What does this print?

const body = JSON.stringify({ title: "Revise maths", done: false });
console.log(typeof body);
console.log(body);

🧩 Your challenge

Weather client: write `getWeather(city)` that fetches `${API}/weather?city=...`, and THROWS an Error with the server's message when res.ok is false. Then loop over ["Mumbai", "Goa", "Jaipur"] and print either "Mumbai: 31°C Humid" or "Goa: City not found" — one bad city must not stop the others. Finish with how many cities worked, e.g. "Loaded 2 of 3".

Expected output in the console:
Mumbai: 31°C Humid
Goa: City not found
Jaipur: 18°C Sunny
Loaded 2 of 3
🟨 JavaScript — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

const API = "https://api.talentjr.in/api/v1/practice";
const data = await fetch(`${API}/quotes/1`).json();
console.log(data.text);

TypeError: fetch(...).json is not a function

✅ Right

const API = "https://api.talentjr.in/api/v1/practice";
const res = await fetch(`${API}/quotes/1`);
const data = await res.json();
console.log(data.text);

.json() runs first, on the Promise that fetch returns, and only then does await act. Await the response on its own line, then await res.json().

❌ Wrong

const API = "https://api.talentjr.in/api/v1/practice";
const res = await fetch(`${API}/weather?city=Goa`);
const data = await res.json();
console.log(`Goa is ${data.temp_c}°C`);

No error, but it prints "Goa is undefined°C" — the server answered 404 with { error: "City not found" }, which has no temp_c.

✅ Right

const API = "https://api.talentjr.in/api/v1/practice";
const res = await fetch(`${API}/weather?city=Goa`);
const data = await res.json();
if (res.ok) console.log(`Goa is ${data.temp_c}°C`);
else console.log("Sorry:", data.error);

fetch does not throw on 404, so always check res.ok before using the data.

❌ Wrong

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

No error, but it prints 422 instead of 201 — the server could not read the body, so nothing was created.

✅ Right

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

The body must be a JSON string plus the Content-Type header. A plain object is sent as the text "[object Object]".

📌 Remember

  • An API client sends requests (GET to read, POST to create) and uses the JSON that comes back.
  • Build query strings with URLSearchParams so spaces and symbols are safe.
  • fetch does not throw on 404 or 500 — always check res.ok and show the server's error message.
  • POST needs method, a Content-Type: application/json header and a JSON.stringify body.
  • Put fetch + check + json in one reusable function and catch its errors where you call it.

Finished the quiz and the challenge?

Questions students ask

What is a REST API in simple words?

A REST API is a set of web addresses for data. Each address is a "thing", like /students/3, and the method says what to do: GET to read, POST to add, PUT to change, DELETE to remove. The answers usually come as JSON.

Why does fetch not throw an error on 404?

For fetch, a 404 is still a successful conversation: the server answered, just with bad news. fetch only rejects when it cannot reach the server at all. That is why every good client checks res.ok.

What is a CORS error?

Browsers block a page from reading another website's API unless that API says "this is allowed". When it does not, you see a CORS error in the console. Our practice API allows every page, so you will not hit it here.

Where do API keys go in a real app?

Many real APIs need a key. Never put a secret key in browser JavaScript, because anyone can read it. Real apps keep keys on their own server and let the server call the API.