Thuta Learning
API Tutorial
BasicWeb DevelopmentIntermediate

API Tutorial HOME

API TutorialLesson 115 min

What you'll walk away with

  • Describe a web API as a contract between a client program and a server program
  • Name the five chapters of the course and what each one builds toward
  • Send a GET request with fetch to a local mock server and read the status, headers and JSON body
  • Explain why the examples here use local mock servers instead of real provider keys

Explain it simply

Explain it simply

An API is a way for one program to ask another program for something, using rules both sides have agreed on. Think of a restaurant: you never walk into the kitchen. You read the menu, tell the waiter what you want, and the waiter brings back a dish. The menu is the documentation, your order is the request, and the dish is the response.

A web API works the same way over the internet. Your app sends an HTTP request to a URL, the server does the work behind the scenes, and a response comes back, usually as JSON. You never see the server's database or code, only the menu it chose to offer.

Problem → Why → Solution

The problem: one working request proves very little

Suppose your app needs the current price of a product, a user's profile, or the result of a payment. That information lives on someone else's computer, and you cannot reach into it. Without an agreed way to ask, every pair of programs would need its own custom connection.

The first attempt at a client usually looks fine on a good day. It sends one request, reads the answer and moves on. The trouble is everything the happy path ignores: the server may answer with an error status, the body may not be what you expected, and the network may fail. The code below crashes the first time it asks for a user that does not exist.

naive-client.mjs
// api.example.com is a placeholder host used for illustration only
const res = await fetch("https://api.example.com/v1/users/42");
const user = await res.json();
console.log(user.name.toUpperCase());

// If user 42 does not exist, the server answers 404 with {"error":"not_found"}:
// TypeError: Cannot read properties of undefined (reading 'toUpperCase')

Why is one working request not enough?

A 200 response proves that one request worked once, for one user, with one key. It says nothing about missing records, expired credentials, slow networks or servers that return errors. This course teaches you to read the status line, the headers and the body separately, so your client handles each outcome on purpose instead of crashing on the first surprise.

Core concept: an API is a contract between two programs

An API (Application Programming Interface) is a contract between two programs. The contract says which requests the server understands and what each answer will look like. Because both sides keep their half of the contract, the client does not need to know whether the server is written in Python, Go or Java, or which database it uses. This lesson and the whole course are about web APIs, which use HTTP as the language of that contract.

Every HTTP exchange has the same two halves. The client sends a request made of a method (what to do), a URL (which thing), headers (extra information such as the format you accept) and sometimes a body (data you send). The server sends back a response made of a status code (how it went), headers and usually a body. Your job as an API user is to build the first half carefully and to read all three parts of the second half, not just the body.

A server never starts the conversation; it only answers requests. That is why a web API is described as request-response, and why every example here has two sides: a server (a mock) and a client that calls it. The client is the code you will write most often. The server might be a provider you do not control, such as a payment company, or a service your own team builds, as you will do yourself in the Projects chapter.

None of the examples in this course needs an internet connection, an account or a secret key. Each runnable sample starts a tiny mock server on your own computer, on a random free port, calls it with fetch and shuts it down again. The output is therefore the same every time you run it, and you can break things safely. Real provider URLs that appear in later lessons are marked as illustrations, because provider details change and you should always confirm them in the official documentation.

Mental model: ask, answer, check
  1. Client sends a request
  2. Server reads method and path
  3. Server returns status, headers, body
  4. Client checks status before the body

Read the three parts of a response in order, and read the body last.

General pattern: a request in a few lines

javascript
const res = await fetch(url, { method, headers, body });
if (!res.ok) {
  throw new Error(`HTTP ${res.status}`);
}
const data = await res.json();

fetch(url, options) starts the request and resolves with a Response object as soon as the server's headers arrive. res.ok is true for status codes 200 to 299. Only after that check is it safe to parse the body with res.json(). The options object is optional: leave it out and you get a plain GET.

Example: your first request to a mock server

This script plays both roles in one file. It starts a mock API that serves the course outline at /api/course, then acts as the client: it sends a GET request, prints the status line and one header, and turns the JSON body into a readable table. Save it as first-request.mjs and run node first-request.mjs (Node 22 or newer). Nothing leaves your machine.

first-request.mjs
import http from "node:http";

const course = {
  title: "API Tutorial",
  chapters: [
    { name: "Basic", lessons: 5 },
    { name: "Intermediate", lessons: 9 },
    { name: "Advanced", lessons: 14 },
    { name: "Projects", lessons: 3 },
    { name: "Exercises", lessons: 2 },
  ],
};

// The mock server: GET /api/course returns JSON, every other request gets a 404.
const server = http.createServer((req, res) => {
  if (req.method === "GET" && req.url === "/api/course") {
    res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
    res.end(JSON.stringify(course));
  } else {
    res.writeHead(404, { "Content-Type": "application/json; charset=utf-8" });
    res.end(JSON.stringify({ error: "not_found" }));
  }
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${server.address().port}`;

// The client: send one request, then read status, header and body separately.
const res = await fetch(`${base}/api/course`);
console.log("Status:", res.status, res.statusText);
console.log("Content-Type:", res.headers.get("content-type"));

const data = await res.json();
let total = 0;
for (const { name, lessons } of data.chapters) {
  console.log(name.padEnd(13) + String(lessons).padStart(2) + " lessons");
  total += lessons;
}
console.log("Total".padEnd(13) + String(total).padStart(2) + " lessons");

server.close();

Code breakdown

  1. Route checkif (req.method === "GET" && req.url === "/api/course") {

    The server looks at the request's method and URL path to decide what to do. Only a request that matches both gets the course back; everything else falls into the 404 branch.

  2. Status and typeres.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });

    This sets the response's status code and a header before any body is written. The Content-Type header tells the client that the body is JSON.

  3. Port 0await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));

    Port 0 asks the operating system for any free port, so it never collides with another program. 127.0.0.1 means only your own machine can call it, and the await waits until the server is really listening.

  4. Send the requestconst res = await fetch(`${base}/api/course`);

    fetch hands back a Response object as soon as the server's headers arrive. The body has not been read yet, but the status and headers are already available.

  5. Read the head firstconsole.log("Status:", res.status, res.statusText);

    Reading the status before the body is a good habit. res.status is the number (200) and res.statusText is the text (OK).

  6. Parse the bodyconst data = await res.json();

    The body arrives as a stream, hence the second await. res.json() parses the text as JSON and rejects with a SyntaxError if it is not valid JSON.

  7. Shut downserver.close();

    Without this, the listening server keeps the Node process alive forever. Always close the server when the script is done.

You should see
Status: 200 OK
Content-Type: application/json; charset=utf-8
Basic         5 lessons
Intermediate  9 lessons
Advanced     14 lessons
Projects      3 lessons
Exercises     2 lessons
Total        33 lessons
The path of one request
  1. Build the request
  2. Send it with fetch
  3. Read status and headers
  4. Check res.ok
  5. Parse the body

Status 2xx

res.json() and use the data

Status 4xx / 5xx

Handle the error status instead of parsing blindly

The five chapters at a glance

The 33 lessons are ordered so that each chapter needs only what the earlier ones taught. Basic gives you the vocabulary and the tools, Intermediate covers proving who you are and reading what comes back, and Advanced covers what real services throw at you. Projects uses everything together, and Exercises is for trying it yourself.

ChapterLessonsWhat you learn
Basic5What an API is, REST, curl and Postman, the parts of an endpoint
Intermediate9Auth (API key, bearer, OAuth 2.0), HTTP methods, response shape, pagination, error handling
Advanced14Four user CRUD lessons, six AI providers, rate limits, CORS, versioning, OpenAPI
Projects3One mini project in three steps: setup, CRUD features, error handling and polish
Exercises2Request fundamentals, then CRUD, pagination and errors combined

How to work through a lesson

1. Check your Node version

Type node --version in a terminal. The course uses Node 22 or newer, where fetch is built in, so there is nothing to install.

2. Type the sample yourself

Save the code in a .mjs file. The copy button in this page works too, but typing it yourself sticks better.

3. Run it, then change one thing

Run node file.mjs and compare the output. Then misspell the path and watch the status change.

bash
node --version
node first-request.mjs

In real projects

Where APIs show up in real projects

Almost every web and mobile app today is built on APIs. A login screen calls an identity API, a checkout page calls a payment provider's API, a map calls a places API, and a chat feature calls an AI provider's API. Even your own frontend and backend are connected by an API you write.

Moving from a demo to production changes the kind of problem you face. Credentials expire, providers limit you when you send too many requests, a new version renames a field, and the network drops now and then. Teams reproduce such problems with tools like curl and Postman and look the exact request and response up in their logs. This course aims to help you expect those situations and connect to services reliably and securely.

Common mistakes

Common mistakes

1. Using the body without checking the status

On a 404 or 500 the body is usually an error message without the fields you expect. Reading user.name then gives undefined, and a TypeError appears further down the code, far from the real cause. Check res.ok first.

2. Expecting fetch to throw on a 404

The promise from fetch rejects only when the request itself fails, such as a dropped network. If the server answers 404 or 500, a response did arrive, so the promise resolves. Do not assume a single try/catch catches HTTP errors.

3. Pasting a real key into practice code

While following a tutorial it is easy to type your real key into a file and commit it to git. Practise against a mock server, and handle real keys only through the environment-variable approach shown in later lessons.

Best practices

Best practices

  • Keep a dedicated folder for the course and save each sample as its own file.
  • Predict the status you expect before every run, then compare it with what you got.
  • Read error messages in full: the cause and status often sit beyond the first line.

Mini challenge

Mini challenge: ping a mock server twice

Write a mock server with two routes, call both from a client and print each status. Parse the body only when res.ok is true.

  • GET /api/ping answers with status 200 and the JSON { pong: true }
  • Every other path answers with status 404 and the JSON { error: "not_found" }
  • The client calls /api/ping and /api/missing and prints each as "<path> -> <status>"
  • Skip JSON parsing when res.ok is false, and close the server at the end
ping.mjs
import http from "node:http";

const server = http.createServer((req, res) => {
  // TODO: GET /api/ping -> 200 and { pong: true }
  // TODO: anything else -> 404 and { error: "not_found" }
});

// TODO: listen on port 0 and build the base URL

// TODO: loop over the two paths, call fetch, print "<path> -> <status>"
// TODO: only call res.json() when res.ok is true

// TODO: close the server

Expected: The output should be: /api/ping -> 200 {"pong":true} /api/missing -> 404 (not ok, body not parsed)

Show hint

Inside the server you can pick the answer with a ternary such as known ? 200 : 404. Call res.json() only inside the if (res.ok) block, and do not forget to close the server.

Show solution
ping.mjs
import http from "node:http";

const server = http.createServer((req, res) => {
  const known = req.method === "GET" && req.url === "/api/ping";
  res.writeHead(known ? 200 : 404, { "Content-Type": "application/json" });
  res.end(JSON.stringify(known ? { pong: true } : { error: "not_found" }));
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = "http://127.0.0.1:" + server.address().port;

for (const path of ["/api/ping", "/api/missing"]) {
  const res = await fetch(base + path);
  if (res.ok) {
    console.log(path, "->", res.status, JSON.stringify(await res.json()));
  } else {
    console.log(path, "->", res.status, "(not ok, body not parsed)");
  }
}

server.close();

Quick quiz 1 / 3

Which sentence describes a web API most accurately?

Quick quiz 2 / 3

Why do the runnable samples start their mock server with server.listen(0, ...)?

Quick quiz 3 / 3

A client calls GET /users/42 and the server returns 404 with {"error":"not_found"}. What happens when the client then runs user.name.toUpperCase()?

What to remember

  • A web API is a contract between client and server spoken over HTTP: a request has a method, URL, headers and body, and a response has a status, headers and body.
  • Read a response in order, status first and body last; a single 200 proves very little.
  • The course has 33 lessons in five chapters: Basic 5, Intermediate 9, Advanced 14, Projects 3, Exercises 2.
  • The samples use a local mock server on port 0 and fetch, so they run offline, without keys, with the same output every time.

RFC 9110 — HTTP Semantics — IETF

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

API Tutorial HOME | Thuta Learning