Thuta Learning
API Tutorial
ProjectsWeb DevelopmentIntermediate

Mini Project — Part 1: Project Setup

API TutorialLesson 2935 min

What you'll walk away with

  • Load an API token and base URL from environment variables or a .env file, and fail early with a clear message when they are missing
  • Build one request() helper that every later call goes through
  • Turn an error response into an ApiError that carries status, code and message
  • Test a client against a local mock server so no real token or network is needed

Explain it simply

Explain it simply

Over the next three lessons you will build user-cli, a small client for a Users API. Part 1 only reads data, Part 2 adds create, edit and delete, and Part 3 makes the client survive slow servers, rate limits and bad responses. Nothing in Part 1 is flashy on purpose: it lays the floor that the other two parts stand on.

Think of a restaurant that is about to open. Before anyone cooks a single dish, the owner decides where the keys are kept, what an order slip looks like and what happens when the kitchen says 'we are out of that'. In this project those three decisions are the config loader, the request() helper and the ApiError class.

Problem → Why → Solution

The problem: one script with the token pasted in

The first version of most API scripts is a single file with the token pasted in and fetch called wherever it is needed. It works on the day you write it. A week later the token has been committed to Git, the same Authorization header is copied into six functions, and one of those copies forgot the Accept header.

Then the API answers 401 with an HTML error page, and the script crashes with a JSON parsing error instead of telling you the token is wrong. The code is not hard; the decisions simply live in the wrong place, spread over every call site.

draft.js
// draft.js: works on the day you write it, hurts a week later
const res = await fetch("https://api.example.com/v1/users?page=1", {
  headers: { Authorization: "Bearer sk_live_51Hxample" }, // secret now lives in Git
});
const body = await res.json();       // throws if the server sent an HTML error page
console.log(body.data.length);       // TypeError when the body is { error: ... }

Why is this fragile?

Credentials, the base URL, headers and error handling are all decided at the call site, so every new call repeats them and every change has to be made everywhere. Moving them behind a config loader and one request() function gives each decision a single home, which is also a single place to test.

Core concept: one config, one request(), one error type

A client library is three decisions made once. The first is configuration: values that differ between machines, such as the base URL and the token, must come from outside the code. Node reads them from process.env, and a .env file is the usual way to fill process.env during development. Since Node 20.6 you can start a script with node --env-file=.env app.mjs, and process.loadEnvFile() does the same from inside a script. The loader should check that the token exists and fail at once with a sentence that names the missing variable, because a request sent with 'Bearer undefined' fails later with a confusing 401.

1. Config: loadConfig(env)

It returns { baseUrl, token } or throws. Taking env as a parameter that defaults to process.env means a test can pass a plain object and never touch the real environment.

2. Transport: request(method, route)

One function joins baseUrl and route, adds the Authorization and Accept headers, calls fetch and parses the JSON. Every endpoint function, such as listUsers() or getUser(), is a thin wrapper that only knows its own route.

3. Failure: ApiError

fetch does not reject when the server answers 404 or 500; it rejects only when no answer arrives at all. So request() checks res.ok itself and throws an ApiError carrying status, code and message from the error body. Callers can then write if (err.status === 404) instead of parsing text.

The second half of the concept is testing all of this without a real provider. The sample starts a small mock server with node:http on port 0, which means 'pick any free port', and it answers in the shapes you met in earlier lessons: { data, meta } for lists and { error: { code, message } } for failures. Because the client only needs a base URL, the same code talks to the mock today and to the real API tomorrow. Print whether a token exists, never the token itself.

ValueWhere it livesWhy
Base URLAPI_BASE_URL, with a defaultDiffers between local, staging and production
TokenAPI_TOKEN in an untracked .env fileIt is a secret and must rotate without a code change
Auth headerBuilt inside request() onlyOne place to change if the scheme changes
Failure shapeApiError with status and codeCallers branch on numbers and codes, not message text
Mental model: floor before walls
  1. Read config once, fail early if missing
  2. Build every call through request()
  3. Check res.ok, throw ApiError on failure
  4. Return plain data to the caller

Callers never see fetch, headers or JSON parsing; they see listUsers() and an ApiError they can branch on.

General pattern

javascript
function loadConfig(env = process.env) { /* read, validate, return { baseUrl, token } */ }

class ApiError extends Error {
  constructor(status, code, message) { /* keep all three on the error */ }
}

function createClient({ baseUrl, token }) {
  async function request(method, route) { /* fetch, check res.ok, parse JSON */ }
  return { /* one thin wrapper per endpoint, built on request() */ };
}

A config loader, an error class and a client factory. request() lives inside the factory, and every endpoint wrapper is built on top of it.

Part 1 code: config, request() and read-only calls

This is the complete file for Part 1. It has three parts: a mock API that plays the role of the provider, the client library you would ship, and a demo that writes a .env file under the OS temp folder, loads it, calls the API and cleans up. The demo prints no token and no port, so every run gives the same output. In your own project, split the first two parts into mock-api.mjs and client.mjs and put export in front of the pieces you import.

Parts 2 and 3 repeat this whole file and mark the new lines, so you can run any part on its own.

part1.mjs
// user-cli, part 1: config + one request() helper + read-only calls.
// Save as part1.mjs and run: node part1.mjs   (Node 20.12 or newer)
// The mock API starts inside this file, so no network or real token is needed.
import http from "node:http";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";

// ===== 1. Mock API: stands in for the real provider =====
const TOKEN = "demo-token-123";
const users = [
  { id: "u_1", name: "Alice", email: "alice@example.com" },
  { id: "u_2", name: "Bob", email: "bob@example.com" },
  { id: "u_3", name: "Chidi", email: "chidi@example.com" },
  { id: "u_4", name: "Dara", email: "dara@example.com" },
  { id: "u_5", name: "Eli", email: "eli@example.com" },
];

function send(res, status, body) {
  res.writeHead(status, { "Content-Type": "application/json" });
  res.end(JSON.stringify(body));
}
function fail(res, status, code, message) {
  send(res, status, { error: { code, message } });
}

const mock = http.createServer((req, res) => {
  if (req.headers.authorization !== `Bearer ${TOKEN}`) {
    return fail(res, 401, "UNAUTHORIZED", "Missing or invalid token");
  }
  const url = new URL(req.url, "http://mock");
  if (req.method === "GET" && url.pathname === "/v1/users") {
    const page = Number(url.searchParams.get("page") ?? 1);
    const limit = Number(url.searchParams.get("limit") ?? 10);
    const data = users.slice((page - 1) * limit, page * limit);
    return send(res, 200, { data, meta: { page, limit, total: users.length } });
  }
  const one = url.pathname.match(/^\/v1\/users\/([\w-]+)$/);
  if (req.method === "GET" && one) {
    const user = users.find((u) => u.id === one[1]);
    if (user) return send(res, 200, { data: user });
    return fail(res, 404, "NOT_FOUND", `User ${one[1]} not found`);
  }
  fail(res, 404, "NOT_FOUND", "No such route");
});

// ===== 2. The client library: the part you would actually ship =====
class ApiError extends Error {
  constructor(status, code, message) {
    super(message);
    this.name = "ApiError";
    this.status = status;
    this.code = code;
  }
}

function loadConfig(env = process.env) {
  const token = env.API_TOKEN;
  if (!token) throw new Error("API_TOKEN is not set (put it in .env, never in code)");
  return { baseUrl: env.API_BASE_URL ?? "https://api.example.com/v1", token };
}

function createClient({ baseUrl, token }) {
  async function request(method, route) {
    const res = await fetch(`${baseUrl}${route}`, {
      method,
      headers: { Authorization: `Bearer ${token}`, Accept: "application/json" },
    });
    const body = await res.json();
    if (!res.ok) throw new ApiError(res.status, body.error.code, body.error.message);
    return body;
  }
  return {
    listUsers({ page = 1, limit = 10 } = {}) {
      return request("GET", `/users?page=${page}&limit=${limit}`);
    },
    async getUser(id) {
      return (await request("GET", `/users/${encodeURIComponent(id)}`)).data;
    },
  };
}

// ===== 3. Demo: load config from a .env file, then call the API =====
const workDir = fs.mkdtempSync(path.join(os.tmpdir(), "user-cli-"));
await new Promise((resolve) => mock.listen(0, "127.0.0.1", resolve));
try {
  try {
    loadConfig({});
  } catch (err) {
    console.log(`config error: ${err.message}`);
  }

  const envFile = path.join(workDir, ".env");
  const { port } = mock.address();
  const envText = `API_BASE_URL=http://127.0.0.1:${port}/v1\nAPI_TOKEN=${TOKEN}\n`;
  fs.writeFileSync(envFile, envText);
  process.loadEnvFile(envFile);
  const client = createClient(loadConfig());

  const first = await client.listUsers({ page: 1, limit: 2 });
  const second = await client.listUsers({ page: 2, limit: 2 });
  console.log("page 1:", first.data.map((u) => u.name).join(", "));
  console.log("page 2:", second.data.map((u) => u.name).join(", "));
  console.log("meta:", JSON.stringify(second.meta));

  const chidi = await client.getUser("u_3");
  console.log(`u_3 -> ${chidi.name} <${chidi.email}>`);

  const wrongToken = createClient({ ...loadConfig(), token: "wrong" });
  for (const call of [() => client.getUser("u_99"), () => wrongToken.listUsers()]) {
    try {
      await call();
    } catch (err) {
      console.log(`${err.name} ${err.status} ${err.code}: ${err.message}`);
    }
  }
} finally {
  mock.close();
  fs.rmSync(workDir, { recursive: true, force: true });
}

Code breakdown

  1. Fail early on missing configif (!token) throw new Error("API_TOKEN is not set (put it in .env, never in code)");

    With no token the loader stops before any request is sent and names the missing variable. Without this check you would send 'Bearer undefined' and meet a confusing 401 later.

  2. Auth header in one placeheaders: { Authorization: `Bearer ${token}`, Accept: "application/json" },

    Headers are built in request() and nowhere else. Endpoint functions never touch them, so one of them can no longer forget Accept.

  3. Turn failures into ApiErrorif (!res.ok) throw new ApiError(res.status, body.error.code, body.error.message);

    fetch does not throw for a 404. This line checks res.ok and throws an ApiError built from the code and message in the error body.

  4. Encode path segments`/users/${encodeURIComponent(id)}`

    An id containing / or ? could end up calling a different route. encodeURIComponent turns those characters into a safe form.

  5. .env into process.envprocess.loadEnvFile(envFile);

    The demo loads a .env file from a temp folder into process.env, and then loadConfig() reads process.env, exactly as it would in a real project.

  6. Port 0 means any free portawait new Promise((resolve) => mock.listen(0, "127.0.0.1", resolve));

    Port 0 lets the OS pick a free port, so the demo never collides with another program. The real port is read back from mock.address().

You should see
config error: API_TOKEN is not set (put it in .env, never in code)
page 1: Alice, Bob
page 2: Chidi, Dara
meta: {"page":2,"limit":2,"total":5}
u_3 -> Chidi <chidi@example.com>
ApiError 404 NOT_FOUND: User u_99 not found
ApiError 401 UNAUTHORIZED: Missing or invalid token

Where the token should and should not live

A token that appears in source code is effectively public, because source code is copied, committed and shared. The usual ladder, from worst to best, is hardcoded in the file, an environment variable on your machine, a .env file that Git ignores, and a secret manager in production. For this project the .env file is enough, but create it with care.

text
# .env   (stays on your machine, holds the real values)
API_BASE_URL=https://api.example.com/v1
API_TOKEN=paste-your-own-token-here

# .gitignore   (committed, so nobody adds .env by accident)
.env

# .env.example   (committed, shows the names without the secrets)
API_BASE_URL=https://api.example.com/v1
API_TOKEN=

A leaked token stays leaked

If a token ever reaches a Git commit, deleting the file does not help, because the history still holds it. Revoke the token in the provider's dashboard and issue a new one.

Redact before you log. The helper below prints the header names but hides the values, so a log line is safe to paste into a bug report.

redact.mjs
// Never log credentials: print headers through a filter like this one
const SECRET_HEADERS = new Set(["authorization", "x-api-key", "cookie"]);

function redactHeaders(headers) {
  const entries = Object.entries(headers).map(([name, value]) => [
    name,
    SECRET_HEADERS.has(name.toLowerCase()) ? "[redacted]" : value,
  ]);
  return Object.fromEntries(entries);
}

const sent = { Authorization: "Bearer demo-token-123", Accept: "application/json" };
console.log(redactHeaders(sent));
console.log("original untouched:", sent.Authorization.length, "characters");

fetch only rejects when there is no answer

New learners often wrap fetch in try/catch and expect a 404 to land in the catch block. It does not. A 404 is a complete, valid HTTP answer, so fetch resolves and only sets res.ok to false. The catch block runs when there is no answer at all, for example because nothing listens on the port.

fetch-vs-status.mjs
import http from "node:http";

const server = http.createServer((req, res) => {
  res.writeHead(404, { "Content-Type": "application/json" });
  res.end(JSON.stringify({ error: { code: "NOT_FOUND" } }));
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const { port } = server.address();

// A 404 is still an answer: fetch resolves and only sets res.ok to false
const res = await fetch(`http://127.0.0.1:${port}/v1/users/u_99`);
console.log("resolved:", res.status, "ok =", res.ok);

// No answer at all is the only thing that makes fetch reject
await new Promise((resolve) => server.close(resolve));
try {
  await fetch(`http://127.0.0.1:${port}/v1/users/u_99`);
} catch (err) {
  console.log("rejected:", err.name, "-", err.message, "-", err.cause.code);
}

The error you see in that second case is a TypeError whose message is just fetch failed; the useful detail, here ECONNREFUSED, sits in err.cause.code. Part 3 reads that code and turns it into an ApiError of its own, so the Part 1 helper deliberately leaves network failures alone for now.

Situationfetch doesrequest() does
Server answers 200Resolves, res.ok is trueReturns the parsed body
Server answers 404 or 500Resolves, res.ok is falseThrows ApiError
Nothing is listeningRejects with TypeError: fetch failedLets the TypeError through (Part 3 wraps it)

In real projects

In real projects

Official SDKs from payment, messaging and cloud providers look like this skeleton from the inside: a configuration object, one internal request function and an error class that carries a status and a code. Reading one with that map in your head turns a thousand lines into three ideas, and it tells you where to look when a call misbehaves.

On a real team the same layout supports everyday workflows. A new teammate clones the repository, copies .env.example to .env, pastes their own token and runs one command. The CI job injects a staging token from its secret store and runs the tests against a mock, so no pipeline ever needs production credentials. And when the provider changes its base URL or rotates keys, you edit an environment variable instead of releasing new code.

Common mistakes

Common mistakes

Committing the .env file

Add .env to .gitignore before the first commit, not after. Once a token is in history, treat it as leaked and revoke it; deleting the file in a later commit protects nothing.

Expecting fetch to throw on 404 or 500

A try/catch around fetch alone lets every error response slip through as if it were data, and the next line fails with a confusing TypeError. Check res.ok, or let request() do it, so a bad status always becomes a visible ApiError.

Gluing user input into paths

A string like `/users/${id}` with id set to "a/b" or "../admin" changes which route is called. Wrap path segments in encodeURIComponent(), as getUser() does, and build query strings with URLSearchParams instead of concatenation.

Mini challenge

Harden the config loader

Make loadConfig() stricter and safer to print. It should trim the token, reject a blank one, default and validate the base URL, remove trailing slashes and refuse anything that is not http or https. Add describeConfig() that reports the token's length instead of the token, then run five different env objects through both functions.

  • A blank or whitespace-only API_TOKEN throws an Error that names API_TOKEN
  • API_BASE_URL defaults to https://api.example.com/v1 and a trailing slash is removed
  • A value new URL() cannot parse, or a protocol other than http and https, throws a clear Error
  • describeConfig() never contains the token, only how many characters it has
config-challenge.mjs
// Harden loadConfig for user-cli. describeConfig must NEVER print the token itself.

function loadConfig(env = process.env) {
  // TODO 1: trim API_TOKEN; throw a clear Error naming API_TOKEN when it is empty
  // TODO 2: default API_BASE_URL to "https://api.example.com/v1" (trim it too)
  // TODO 3: reject anything new URL() cannot parse, and any protocol except http/https
  // TODO 4: strip trailing slashes so baseUrl + "/users" never has a double slash
  // return { baseUrl, token };
}

function describeConfig(config) {
  // TODO 5: return one line with the base URL and how many characters the token has
}

// TODO 6: try five env objects (valid, defaults, blank token, no scheme, ftp://)
//         and print "ok: ..." or "error: ..." for each

Expected: Five lines: two ok lines with the base URL and a token length (the first one with its trailing slash and spaces cleaned up), then one error each for the blank token, the URL without a scheme and the ftp URL.

Show hint

new URL(text) throws a TypeError for text without a scheme, so wrap it in try/catch. parsed.protocol includes the colon, for example "https:". Use replace(/\/+$/, "") to strip trailing slashes.

Show solution
config-challenge.mjs
function loadConfig(env = process.env) {
  const token = (env.API_TOKEN ?? "").trim();
  if (!token) throw new Error("API_TOKEN is not set (put it in .env, never in code)");

  const rawUrl = (env.API_BASE_URL ?? "https://api.example.com/v1").trim();
  let parsed;
  try {
    parsed = new URL(rawUrl);
  } catch {
    throw new Error(`API_BASE_URL is not a valid URL: "${rawUrl}"`);
  }
  if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
    throw new Error(`API_BASE_URL must use http or https, got ${parsed.protocol}`);
  }
  return { baseUrl: rawUrl.replace(/\/+$/, ""), token };
}

function describeConfig({ baseUrl, token }) {
  return `base URL ${baseUrl}, token set (${token.length} characters)`;
}

const cases = [
  { API_TOKEN: " abc123 ", API_BASE_URL: "http://localhost:8080/v1/" },
  { API_TOKEN: "abc123" },
  { API_TOKEN: "   " },
  { API_TOKEN: "abc123", API_BASE_URL: "api.example.com/v1" },
  { API_TOKEN: "abc123", API_BASE_URL: "ftp://files.example.com" },
];
for (const env of cases) {
  try {
    console.log("ok:", describeConfig(loadConfig(env)));
  } catch (err) {
    console.log("error:", err.message);
  }
}

Quick quiz 1 / 3

request() contains if (!res.ok) throw new ApiError(...). The server answers GET /users/u_99 with status 404 and a JSON error body. What does the caller of getUser("u_99") see?

Quick quiz 2 / 3

Why does loadConfig take env as a parameter that defaults to process.env?

Quick quiz 3 / 3

A teammate adds console.log(config) to debug in CI. What is the problem?

What to remember

  • Read the base URL and token from the environment, and fail early with a message that names the missing variable
  • Send every call through one request() helper so headers and error handling live in one place
  • fetch resolves on 404 and 500; request() must check res.ok and throw an ApiError with status, code and message
  • Test against a mock server on port 0 so no real token or network is needed

OWASP API Security Project — OWASP

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.

Mini Project — Part 1: Project Setup | Thuta Learning