Project: Build a REST API Checker with JavaScript fetch

The final project is the most “QA” of the three: an API checker that reads a list of endpoints from a JSON file, calls them with fetch, verifies status codes, JSON values and response-time budgets, retries flaky network errors, prints a readable report, saves a JSON report and fails the build when something is wrong. Teams run tools like this as smoke tests after every deployment and on a schedule to watch staging. It brings together fetch and error handling (Module 10), files and environment variables (Module 11), design patterns and performance ideas (Module 13) and unit testing (Module 14). Every result on this page comes from a real run against a small demo API that ships with the project.

Advertisement

📖 What You’ll Learn: how to design config-driven checks, separating pure evaluation logic from network I/O, reading nested JSON values by path, fetch with AbortSignal.timeout, measuring response time, retrying only network errors, running requests with a concurrency limit, building a readable report, saving a JSON report, exit codes for CI, configuring the target with environment variables, unit-testing the evaluation logic, and scheduling the checker in GitHub Actions.


📋 Requirements and Design

#Requirement
R1Checks are defined in checks.json, not in code, so testers can add endpoints without programming
R2Each check can assert the status code, values in the JSON body (including nested paths) and a maximum response time
R3Requests time out after 3 seconds; network errors are retried once; HTTP errors are not retried
R4At most 3 requests run at the same time (do not overload the server)
R5The report lists every check with ✓ or ✗ and the exact problems; a JSON report is saved
R6The exit code is 1 if any check fails, so CI pipelines stop
R7The target URL comes from the BASE_URL environment variable

📁 Project structure

api-checker/
├── checks.json      what to check (data)
├── checker.js       evaluate (pure) + request, runChecks, formatReport
├── check-api.js     entry point: config, run, report, exit code
├── demo-api.js      a demo API to practise against
└── checker.test.js  unit tests

🗂️ Step 1: Checks as Data

Each check names an endpoint and its expectations. Nested JSON values use a dotted path such as address.city, and length works on arrays because arrays have a length property:

📄 checks.json

[
  { "name": "health", "path": "/health", "expect": { "status": 200, "maxMs": 500, "json": { "status": "ok" } } },
  { "name": "list users", "path": "/api/users", "expect": { "status": 200, "maxMs": 500, "json": { "length": 2 } } },
  { "name": "user 1 city", "path": "/api/users/1", "expect": { "status": 200, "json": { "address.city": "Pune" } } },
  { "name": "orders (slow)", "path": "/api/orders", "expect": { "status": 200, "maxMs": 300 } },
  { "name": "payments", "path": "/api/payments", "expect": { "status": 200 } },
  { "name": "stock (flaky network)", "path": "/api/stock", "expect": { "status": 200, "json": { "inStock": 12 } } },
  { "name": "missing page", "path": "/api/nope", "expect": { "status": 404 } }
]

The demo API has every situation a real API produces: healthy endpoints, a slow one, a broken one (500), one whose connection drops on the first call, and a missing route:

📄 demo-api.js

import http from "node:http";

// A small demo API with healthy, slow, broken and flaky endpoints
let flakyCalls = 0;

export function startDemoApi(port = 0) {
  const server = http.createServer((req, res) => {
    const send = (status, body, delay = 0) => setTimeout(() => {
      res.writeHead(status, { "content-type": "application/json" });
      res.end(JSON.stringify(body));
    }, delay);

    if (req.url === "/health") return send(200, { status: "ok", version: "2.4.1" });
    if (req.url === "/api/users") return send(200, [{ id: 1, name: "Asha" }, { id: 2, name: "Ravi" }]);
    if (req.url === "/api/users/1") return send(200, { id: 1, name: "Asha", address: { city: "Pune" } });
    if (req.url === "/api/orders") return send(200, { orders: [] }, 600);            // slow
    if (req.url === "/api/payments") return send(500, { error: "gateway down" });    // broken
    if (req.url === "/api/stock") return ++flakyCalls === 1 ? req.socket.destroy() : send(200, { inStock: 12 });  // fails once
    send(404, { error: "not found" });
  });
  return new Promise((resolve) => server.listen(port, () => resolve(server)));
}

Advertisement

⚙️ Step 2: The Checker

The checker has a pure part, evaluate(), that turns a check and a result into a list of problems, and an I/O part that makes the requests. That split makes the logic testable without any network:

📄 checker.js

// ---------- pure helpers (unit tested) ----------
export const getPath = (obj, path) => path.split(".").reduce((value, key) => value?.[key], obj);

export function evaluate(check, result) {
  const { status: wantStatus = 200, maxMs, json = {} } = check.expect;
  const problems = [];
  if (result.error) return [`request failed: ${result.error}`];
  if (result.status !== wantStatus) problems.push(`status ${result.status}, expected ${wantStatus}`);
  if (maxMs && result.ms > maxMs) problems.push(`took ${Math.round(result.ms / 100) * 100} ms, budget ${maxMs} ms`);
  for (const [path, want] of Object.entries(json)) {
    const got = getPath(result.body, path);
    if (got !== want) problems.push(`${path} is ${JSON.stringify(got)}, expected ${JSON.stringify(want)}`);
  }
  return problems;
}

// ---------- I/O: one request, with timeout and retry on network errors ----------
export async function request(baseURL, check, { timeoutMs = 3000, retries = 1 } = {}) {
  for (let attempt = 1; ; attempt++) {
    const start = performance.now();
    try {
      const res = await fetch(new URL(check.path, baseURL), {
        method: check.method ?? "GET",
        headers: check.headers,
        signal: AbortSignal.timeout(timeoutMs),
      });
      const text = await res.text();
      let body = text;
      try { body = JSON.parse(text); } catch { /* not JSON: keep the text */ }
      return { status: res.status, ms: performance.now() - start, body, attempts: attempt };
    } catch (error) {
      if (attempt > retries) return { error: error.cause?.code ?? error.name, attempts: attempt };
    }
  }
}

// ---------- run many checks, at most `concurrency` at a time ----------
export async function runChecks(baseURL, checks, { concurrency = 3 } = {}) {
  const results = new Array(checks.length);
  let next = 0;
  async function worker() {
    while (next < checks.length) {
      const i = next++;
      const result = await request(baseURL, checks[i]);
      results[i] = { name: checks[i].name, ...result, problems: evaluate(checks[i], result) };
    }
  }
  await Promise.all(Array.from({ length: concurrency }, worker));
  return results;
}

export function formatReport(results) {
  const lines = results.map((r) => {
    const mark = r.problems.length ? "✗" : "✓";
    const retry = r.attempts > 1 ? ` (after ${r.attempts} attempts)` : "";
    return `${mark} ${r.name.padEnd(22)} ${String(r.status ?? "-").padEnd(4)}${retry}${r.problems.map((p) => `\n    - ${p}`).join("")}`;
  });
  const failed = results.filter((r) => r.problems.length).length;
  lines.push(`\n${results.length - failed}/${results.length} checks passed`);
  return lines.join("\n");
}
  • Timeouts: AbortSignal.timeout(3000) cancels a hanging request (Module 10).
  • Retries: only when fetch throws (connection refused or dropped, timeout). A 500 is a real answer, so it is reported, not retried.
  • Concurrency limit: three “workers” take the next check from a shared index until none are left, a simple promise pool.
  • Safe JSON: the body is read as text first, then parsed, so an HTML error page does not crash the checker.

The entry point reads the config and the base URL, prints the report, saves api-report.json and sets the exit code:

📄 check-api.js

import { readFile, writeFile } from "node:fs/promises";
import { runChecks, formatReport } from "./checker.js";

const baseURL = process.env.BASE_URL ?? "http://localhost:3000";
const checks = JSON.parse(await readFile("checks.json", "utf8"));

console.log(`Checking ${checks.length} endpoints on ${baseURL}\n`);
const results = await runChecks(baseURL, checks);
console.log(formatReport(results));

await writeFile("api-report.json", JSON.stringify({ baseURL, results }, null, 2));
process.exitCode = results.some((r) => r.problems.length) ? 1 : 0;      // CI fails if any check failed

▶️ Step 3: Run It

In real use you run BASE_URL=https://staging.example.com node check-api.js. To practise, this small script starts the demo API on a free port and runs the checker against it:

📄 run-demo.js

import { startDemoApi } from "./demo-api.js";

// start the demo API, point the checker at it, run it, then stop the API
const api = await startDemoApi(3000);
process.env.BASE_URL = "http://localhost:3000";
await import("./check-api.js");
api.close();

⌨️ Terminal

node run-demo.js

🖥️ Output

Checking 7 endpoints on http://localhost:3000

✓ health                 200 
✓ list users             200 
✓ user 1 city            200 
✗ orders (slow)          200 
    - took 600 ms, budget 300 ms
✗ payments               500 
    - status 500, expected 200
✓ stock (flaky network)  200  (after 2 attempts)
✓ missing page           404 

5/7 checks passed

Five checks passed and two failed, each with a precise reason:

  • orders (slow): it answered correctly but took about 600 ms against a 300 ms budget: a performance regression.
  • payments: a real 500 error, reported immediately and not retried.
  • stock: the first connection was dropped; the retry succeeded, so it passed, and the report shows the retry so flakiness stays visible.
  • missing page: expecting 404 is a valid check too (negative test).
  • Exit code 1: the build output marks this run as failed, exactly what makes a CI job stop.

📌 Note: The timings are rounded to 100 ms in the report because they vary slightly between runs; the slow endpoint is always around 600 ms.


Advertisement

🧪 Step 4: Unit-Test the Logic

The pure helpers are tested with fake results, so the tests are instant and never depend on a real server:

📄 checker.test.js

import { describe, it } from "node:test";
import assert from "node:assert/strict";
import { getPath, evaluate, formatReport } from "./checker.js";

describe("getPath", () => {
  it("reads nested values and returns undefined safely", () => {
    const body = { user: { address: { city: "Pune" } }, list: [1, 2] };
    assert.equal(getPath(body, "user.address.city"), "Pune");
    assert.equal(getPath(body, "list.length"), 2);
    assert.equal(getPath(body, "user.phone.number"), undefined);
  });
});

describe("evaluate", () => {
  const check = { expect: { status: 200, maxMs: 500, json: { "user.name": "Asha" } } };
  it("passes a good result", () => {
    assert.deepEqual(evaluate(check, { status: 200, ms: 120, body: { user: { name: "Asha" } } }), []);
  });
  it("reports every problem at once", () => {
    const problems = evaluate(check, { status: 503, ms: 1250, body: { user: { name: "Ravi" } } });
    assert.deepEqual(problems, [
      "status 503, expected 200",
      "took 1300 ms, budget 500 ms",
      'user.name is "Ravi", expected "Asha"',
    ]);
  });
  it("reports network errors", () => {
    assert.deepEqual(evaluate(check, { error: "ECONNREFUSED" }), ["request failed: ECONNREFUSED"]);
  });
});

describe("formatReport", () => {
  it("summarises passed and failed checks", () => {
    const text = formatReport([
      { name: "a", status: 200, attempts: 1, problems: [] },
      { name: "b", status: 500, attempts: 1, problems: ["status 500, expected 200"] },
    ]);
    assert.match(text, /✓ a/);
    assert.match(text, /✗ b[\s\S]*status 500/);
    assert.match(text, /1\/2 checks passed$/);
  });
});

⌨️ Terminal

node --test checker.test.js

🖥️ Output

▶ getPath
  ✔ reads nested values and returns undefined safely (0.7138ms)
✔ getPath (1.694ms)
▶ evaluate
  ✔ passes a good result (0.7725ms)
  ✔ reports every problem at once (0.2696ms)
  ✔ reports network errors (0.1276ms)
✔ evaluate (1.5563ms)
▶ formatReport
  ✔ summarises passed and failed checks (0.4035ms)
✔ formatReport (0.5222ms)
ℹ tests 5
ℹ suites 3
ℹ pass 5
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 157.5653

⏰ Step 5: Run It on a Schedule in CI

Because the checker exits with code 1 on failure, any CI system can run it. This GitHub Actions workflow runs after every push and every 30 minutes, and keeps the JSON report as an artifact:

📄 .github/workflows/api-checks.yml

name: API smoke checks
on:
  push:
  schedule:
    - cron: "*/30 * * * *"      # every 30 minutes
jobs:
  check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 24
      - run: node check-api.js
        env:
          BASE_URL: https://staging.example.com
      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: api-report
          path: api-report.json

💡 Tip: Add an authorization header to a check with "headers": { "authorization": "Bearer ..." }, but never commit tokens: read them from an environment variable (a CI secret) in check-api.js and add them to the checks at runtime.


🚀 Extend the Project

ExtensionSkills practised
POST/PUT checks with a JSON bodyfetch options, cleaning up created data
Validate full response shapes with a JSON Schema (e.g. the ajv library)npm packages, contract testing
Run against several environments (--env staging)parseArgs, config per environment
Write a JUnit XML reportString building and escaping; CI test reports
Send a Slack or Teams message when a check failsWebhooks with fetch, secrets
Track response times over many runsFiles or a database, simple statistics (median, p95)
Move the same checks into Playwright’s request fixturePlaywright API testing, shared reports

You have now built a browser app, a CLI and an API tool, and tested all three. That is a portfolio worth putting on GitHub, and Module 16 prepares you for the interview that follows.


Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Add a check to checks.json that expects /health to return version “2.4.1”.

Show answer
{ "name": "health version", "path": "/health", "expect": { "status": 200, "json": { "version": "2.4.1" } } }

Q2. Use getPath to read orders.0.items.1.sku from a nested object.

Show answer

📄 practice2.js

const getPath = (obj, path) => path.split(".").reduce((value, key) => value?.[key], obj);
const body = { orders: [{ items: [{ sku: "A1" }, { sku: "B2" }] }] };
console.log(getPath(body, "orders.0.items.1.sku"), getPath(body, "orders.5.items"));

🖥️ Output

B2 undefined

Q3. Why does the checker retry a dropped connection but not a 500 response?

Show answer

A thrown fetch error means there was no answer at all, often a short network blip, so one retry is reasonable. A 500 is a real answer from the server reporting a failure; retrying could hide a genuine bug or trigger a duplicate action, so it is reported straight away. The report still shows when a retry happened, so flakiness is not hidden.

Q4. Write a tiny promise pool runLimited(tasks, limit) and show that at most 2 tasks run at once.

Show answer

📄 practice4.mjs

async function runLimited(tasks, limit) {
  let next = 0, running = 0, maxRunning = 0;
  const results = [];
  async function worker() {
    while (next < tasks.length) {
      const i = next++;
      running++;
      maxRunning = Math.max(maxRunning, running);
      results[i] = await tasks[i]();
      running--;
    }
  }
  await Promise.all(Array.from({ length: limit }, worker));
  return { results, maxRunning };
}
const sleep = (ms, v) => () => new Promise((r) => setTimeout(() => r(v), ms));
console.log(await runLimited([sleep(30, "a"), sleep(10, "b"), sleep(20, "c"), sleep(5, "d")], 2));

🖥️ Output

{ results: [ 'a', 'b', 'c', 'd' ], maxRunning: 2 }

Q5. How would you make the checker fail if the API is slower than 1 second on average across all checks?

Show answer

After runChecks, compute the average of r.ms for results without errors, print it, and set process.exitCode = 1 when it exceeds 1000. Better still, use the median or 95th percentile, which are less affected by one slow outlier.

Q6. A check against production should never create data. Which kinds of checks are safe to run there?

Show answer

Read-only requests (GET of health, public listings, a known test record), with a dedicated monitoring account if authentication is needed, low frequency and a concurrency limit. Avoid POST/PUT/DELETE unless they act on clearly marked test data that is cleaned up, and agree the plan with the team that owns production.


🧠 MCQ Quiz: Project: API Checker

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Why are the checks stored in checks.json?
  2. What does getPath(body, “address.city”) do?
  3. Which errors does the checker retry?
  4. How is a hanging request stopped?
  5. Why limit concurrency to 3?
  6. What does evaluate() return for a passing check?
  7. Why read the body with text() first?
  8. How does CI know the checks failed?
  9. Where should the target URL come from?
  10. Which part of the checker is unit tested without a network?

💼 Interview Questions and Answers

Q1. How would you build a quick smoke test for a set of REST APIs?

Describe the endpoints and expectations as data (status, key JSON fields, response-time budget), call them with fetch or Playwright’s request fixture using timeouts, evaluate results with pure functions, retry only transient network errors, limit concurrency, print a clear report and a machine-readable one, exit non-zero on failure, and run it after every deployment and on a schedule against each environment.

Q2. What do you check in an API response besides the status code?

Headers such as content-type and caching, the body structure (required fields, types, no unexpected nulls), business values, error formats for negative cases, response time, pagination and limits, and security aspects such as authentication being required and sensitive fields not exposed. JSON Schema validation automates structural checks.

Q3. How do you avoid flaky API checks?

Use generous timeouts, retry only network-level failures (and show the retries in reports), avoid depending on data that changes (use dedicated test records or create and clean up your own), control concurrency, keep checks independent, and use percentiles rather than single response times for performance budgets.

Q4. Why separate evaluate() from request()?

evaluate() is pure: given a check and a result, it returns problems. It can be unit tested with any combination of status, body and timing in milliseconds, without a server. request() contains the side effects (network, timing, retries) and is covered by running the tool against the demo API. This split is the same pattern used in the to-do and CLI projects.


Advertisement

❓ Frequently Asked Questions

🤔 Should I use this instead of Postman or Playwright API tests?

It is a learning project and a lightweight smoke checker. Postman/Newman and Playwright’s request fixture offer more features for full API test suites; the design ideas (data-driven checks, timeouts, clear reports, exit codes) apply to all of them.

🤔 Can it test APIs that need login?

Yes: call the login endpoint first, read the token from the response, and add it to each check’s headers. Store credentials in environment variables or CI secrets, never in checks.json.

🤔 How do I check response headers?

Return Object.fromEntries(res.headers) from request() and add a “headers” section to the expectations, evaluated the same way as the JSON values.

🤔 Where can I practise API testing online?

SQA Tools has a practice REST API and API testing tutorials; point BASE_URL at a practice API and write checks for its endpoints.


🏁 Summary

  • Describe checks as data: path, expected status, JSON values by dotted path and a time budget.
  • Keep evaluate() pure and testable; keep requests, timing, timeouts and retries in a separate function.
  • Retry only network errors, limit concurrency with a small promise pool, and read bodies safely.
  • Print a clear ✓/✗ report, save JSON, and set exit code 1 so CI fails on any problem.
  • Unit-test the logic, run against a demo API, and schedule the checker against each environment.

Next, continue with Lesson 75: Interview Questions: Freshers. This completes Module 15 and the projects. Module 16 is interview preparation: questions for freshers, experienced and senior roles, coding programs and a cheat sheet.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in