Thuta Learning
API Tutorial
BasicWeb DevelopmentIntermediate

What Is an API?

API TutorialLesson 220 min

What you'll walk away with

  • Distinguish a library API (a function call) from a web API (a request over HTTP)
  • Name the three things a client must know about a web API: where it lives, what to send and what comes back
  • Read a response as status, headers and body, and parse the JSON body
  • Explain why an API contract lets the server change internally without breaking clients

Explain it simply

Explain it simply

An API is the front desk of a program. A hotel guest does not walk into the laundry or the accounts office; they ask the front desk, and the front desk knows who to talk to behind the scenes. Programs work the same way. One program exposes a small, documented list of things you may ask for, and hides everything else.

When the two programs run on different machines and talk over the internet using HTTP, the interface is called a web API. That is the kind this course is about: you send a URL and a method, and you get a status, some headers and, usually, a JSON body back.

Problem → Why → Solution

The problem: clients that know the database directly

Imagine you maintain a shop's mobile app, and the product data lives in a server run by another team. Without an API, your app would need the database password, knowledge of the tables and the SQL to read them. The day the other team renames a column, your app breaks, and so does every other app that copied the same trick.

The alternative hides the database and offers a URL such as /products/1 that returns a product as JSON. Clients depend on the URL and the JSON shape only. The code below puts the fragile direct approach next to the stable one.

two-approaches.mjs
// Fragile: the client knows the table layout and holds the database password
const rows = await db.query(
  "SELECT product_name, price_cents FROM tbl_products_v2 WHERE id = 1",
  DB_PASSWORD
);

// Stable: the client knows one URL and the shape of the JSON it returns
// (api.example.com is a placeholder host used for illustration only)
const res = await fetch("https://api.example.com/v1/products/1");

Why does the line between them matter?

Direct database access spreads internal details across every client, so any change inside the server becomes a breaking change outside it. An API draws a line: the server promises a URL, a method and a response shape, and is free to change everything behind that line. That promise is why one API can serve a website, an Android app and a partner's script at the same time.

Core concept: use the interface, skip the implementation

The word API covers more than web services. Whenever code exposes functions for other code to call, that is an API: the functions in Node's built-in crypto module are an API, and so is the list of methods on an array. What they share is an interface you can use without reading the implementation. A web API is the same idea stretched across a network: instead of calling a function, the client sends an HTTP request, and instead of a return value, it receives an HTTP response.

That stretch adds three new facts of life. First, calls take time and can fail for reasons your code did not cause: the server is down, the connection drops or the answer takes too long. Second, data crosses the network as text, so objects must be turned into a format such as JSON on one side and parsed back on the other. Third, the two programs are written and released by different people, so they can rely only on what the contract says.

A client needs to know three things to use a web API. Where it lives: the base URL and the path of the resource. What to send: the method and any query parameters, headers and body the endpoint expects. What comes back: the status codes it can return and the shape of the JSON. API documentation exists to answer exactly these questions, which is why a well-documented API is so much easier to work with than a clever but undocumented one.

A response always has three parts, and learners often look at only one. The status code tells you whether the request worked: 2xx for success, 4xx when the client asked for something wrong, 5xx when the server failed. The headers describe the response; for example, Content-Type: application/json tells you how to read the body. The body carries the data itself. Reading them in that order, status then headers then body, prevents most beginner bugs. Finally, the contract needs a stable shape: a server can add a new field without breaking you, but renaming or removing one breaks every client that relied on it, which is why mature APIs version their changes (covered in the Advanced chapter).

Mental model: a front desk
  1. Client asks the front desk
  2. Front desk checks the request
  3. Back office does the work
  4. Answer returns as status and body

The client only ever sees the front desk, never what happens in the back office.

General pattern: the three parts of a response

javascript
const res = await fetch("https://host/path");
res.status;             // number: how it went
res.headers.get(name);  // string or null: describes the body
await res.json();       // the parsed body, when it is JSON

After fetch resolves, res.status is a number, res.headers.get(name) is the value of one header (or null when it is absent), and res.json() is a promise for the parsed body. A body can be read only once, so do not call res.json() twice on the same response.

Example: the front desk and the back office

The server in this script holds a field (passwordHash) that a client must never see, and the API strips it before answering. The client asks for user 1 and gets a 200, then for user 2, who does not exist, and gets a 404. For each call it prints the status, the Content-Type header and the body separately.

front-desk.mjs
import http from "node:http";

// The back office: data the client never sees.
const users = new Map([
  [1, { id: 1, name: "Alice", email: "alice@example.com", passwordHash: "x9f2" }],
]);

// The front desk: the API exposes only what it chooses to.
const server = http.createServer((req, res) => {
  const match = req.url.match(/^\/users\/(\d+)$/);
  const user = match && users.get(Number(match[1]));
  if (req.method === "GET" && user) {
    const { passwordHash, ...publicUser } = user;
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify(publicUser));
  } else {
    res.writeHead(404, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ error: "user_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 sees only a request, a status, headers and a body.
for (const id of [1, 2]) {
  const res = await fetch(`${base}/users/${id}`);
  console.log(`GET /users/${id} -> ${res.status}`);
  console.log("  content-type:", res.headers.get("content-type"));
  console.log("  body:", JSON.stringify(await res.json()));
}

server.close();

Code breakdown

  1. Hidden data[1, { id: 1, name: "Alice", email: "alice@example.com", passwordHash: "x9f2" }],

    The record in the Map carries an internal field, passwordHash. A client cannot touch this data directly; only the API stands between them.

  2. Route matchingconst match = req.url.match(/^\/users\/(\d+)$/);

    The regular expression captures the digits after /users/. For /users/1, match[1] is "1"; for /users/abc nothing matches, so the answer is a 404.

  3. Choosing what to exposeconst { passwordHash, ...publicUser } = user;

    Destructuring pulls passwordHash out and gathers the rest into publicUser, which is why the response contains only id, name and email.

  4. Request from the clientconst res = await fetch(`${base}/users/${id}`);

    On the client side it is just one URL. Whether the server uses a Map or a database, the client neither knows nor needs to know.

  5. Three parts, one at a timeconsole.log(" content-type:", res.headers.get("content-type"));

    Notice that status, header and body are read separately. Even on the 404 the Content-Type is application/json and the body describes the error, which is a perfectly normal API answer.

You should see
GET /users/1 -> 200
  content-type: application/json
  body: {"id":1,"name":"Alice","email":"alice@example.com"}
GET /users/2 -> 404
  content-type: application/json
  body: {"error":"user_not_found"}

Library API versus web API

Node's crypto module is a good example of a library API. Calling createHash is a function call inside the same process, and the result is available immediately. The table below shows how a web API differs.

library-api.mjs
import { createHash } from "node:crypto";

// A library API: a function call inside the same process.
const digest = createHash("sha256").update("hello").digest("hex");
console.log(digest.slice(0, 12));
AspectLibrary APIWeb API
How you call itA function callAn HTTP request
How it failsAn exception in your own processNetwork errors, timeouts, error statuses
Data formatValues in memoryText over the network (JSON)
Who controls changeYou, when you update the dependencyThe provider, on its own release schedule

Data crosses the wire as text

No JavaScript object travels over the network, only text. JSON.stringify turns an object into text and JSON.parse turns it back. Along the way, anything JSON has no type for gets lost: a Date becomes a string, and keys whose value is undefined disappear.

json-roundtrip.mjs
const order = {
  id: 7,
  paid: true,
  shippedAt: new Date("2025-01-15T10:00:00Z"),
  note: undefined,
};

const text = JSON.stringify(order);
console.log(text);

const back = JSON.parse(text);
console.log(typeof back.shippedAt, back.note);

So when an API sends a date as a string like "2025-01-15T10:00:00.000Z", nothing is wrong: the client turns it back with new Date(value) when it needs a Date.

In real projects

What an API does in real projects

A company often has a website, an iOS app, an Android app and an admin tool. All of them call one backend API, so business rules such as how a price is calculated live in a single place. In systems split into many small services, one service calls another through an internal API in just the same way.

Teams also plug other companies' APIs into their products: payments, email delivery, maps and AI models. Many providers ship curl examples together with SDKs (ready-made client libraries) for languages such as JavaScript and Python. An SDK still sends plain HTTP requests underneath, so once you understand requests, statuses and bodies you can use an SDK with confidence and debug it when something goes wrong. Good documentation directly improves the developer experience, so weigh the quality of the docs when you choose an API.

Common mistakes

Common mistakes

1. Treating a network call like a plain function call

A local function returns instantly and nearly always succeeds, but a web API call can be slow, can drop and can come back with an error status. Without a timeout and a failure branch, one dropped connection can freeze a whole app.

2. Copying only the happy-path example from the docs

The first example in the docs usually shows only the success case. Read the section on error responses too, which statuses can come back and what the error body looks like, or the first 401, 404 or 429 will surprise you in production.

3. Depending on fields the docs never promised

Not everything you can see in a response is part of the contract. If you rely on a field the docs do not mention, it can vanish the next time the provider changes something, with no warning. Use only documented fields.

Best practices

Best practices

  • Call a new API once with curl before writing any code, so you see a real response with your own eyes.
  • Keep the base URL in a single constant, so switching between staging and production is a one-line change.
  • Wrap the call in a function of your own, so the rest of your code never depends on the provider's raw JSON shape.

Mini challenge

Mini challenge: a product API with a public view

Write a mock server whose products each carry an internal costPrice you do not want to expose. The API returns only id, name and price, and a client function getProduct(base, id) returns the product, or null on a 404.

  • Store two products in a Map, each with id, name, price and costPrice
  • GET /products/<id> returns only id, name and price with a 200, or a 404 with { error: "product_not_found" }
  • getProduct returns the parsed object on 200, null on 404 and throws an Error for any other status
  • Print product 1 and the missing product 9, then close the server
products-api.mjs
import http from "node:http";

const products = new Map([
  // TODO: two products with id, name, price and an internal costPrice
]);

const server = http.createServer((req, res) => {
  // TODO: match GET /products/<id>
  // TODO: 200 with only id, name and price, or 404 with { error: "product_not_found" }
});

async function getProduct(base, id) {
  // TODO: fetch the product, return the parsed object for 200 and null for 404
}

// TODO: start the server on port 0, print products 1 and 9, close the server

Expected: The output should be: {"id":1,"name":"Tea","price":1200} null

Show hint

Use const { costPrice, ...publicProduct } = product to drop the internal field. Inside getProduct, check res.status === 404 first and res.ok afterwards.

Show solution
products-api.mjs
import http from "node:http";

const products = new Map([
  [1, { id: 1, name: "Tea", price: 1200, costPrice: 700 }],
  [2, { id: 2, name: "Rice", price: 3400, costPrice: 2900 }],
]);

const server = http.createServer((req, res) => {
  const match = req.url.match(/^\/products\/(\d+)$/);
  const product = match && products.get(Number(match[1]));
  res.setHeader("Content-Type", "application/json");
  if (req.method === "GET" && product) {
    const { costPrice, ...publicProduct } = product;
    res.writeHead(200);
    res.end(JSON.stringify(publicProduct));
  } else {
    res.writeHead(404);
    res.end(JSON.stringify({ error: "product_not_found" }));
  }
});

async function getProduct(base, id) {
  const res = await fetch(base + "/products/" + id);
  if (res.status === 404) return null;
  if (!res.ok) throw new Error("HTTP " + res.status);
  return res.json();
}

await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = "http://127.0.0.1:" + server.address().port;
console.log(JSON.stringify(await getProduct(base, 1)));
console.log(JSON.stringify(await getProduct(base, 9)));
server.close();

Quick quiz 1 / 3

What is the main benefit of putting an API between a client and a database?

Quick quiz 2 / 3

After JSON.parse(JSON.stringify({ n: 1, d: new Date(0), u: undefined })), what happened to d and u?

Quick quiz 3 / 3

Compared with a normal function call, what does a web API call add?

What to remember

  • An API is an interface you use without reading the implementation; a web API stretches it across a network as an HTTP request and response.
  • A client needs to know where the API lives, what to send and what comes back, and reads a response as status, headers, then body.
  • Data crosses the network as text (JSON), so a Date turns into a string and keys with undefined values disappear.
  • Network calls can fail for reasons you do not control, so plan error handling from the start.

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.

What Is an API? | Thuta Learning