Thuta Learning
API Tutorial
ProjectsWeb DevelopmentIntermediate

Mini Project — Part 2: Adding CRUD Features

API TutorialLesson 3040 min

What you'll walk away with

  • Send POST and PATCH requests with a JSON body and a Content-Type header
  • Handle a 204 No Content response without calling res.json()
  • Read field-level details from a 422 response and recognise a 409 conflict through ApiError
  • Map command-line arguments onto client calls and print one readable line per outcome

Explain it simply

Explain it simply

Part 1 could only read. Part 2 adds the three verbs that change data: POST to create, PATCH to edit and DELETE to remove. The Authorization header does not change, because request() already adds it, so the new code is about two things: what goes in the body and what comes back.

Picture a form at a counter. Creating hands over a new form, editing hands over only the boxes you changed, and deleting hands over nothing but the form number. Each of those needs the clerk to answer in a way you can read: stamped, rejected for a missing box, or 'that number does not exist'.

Problem → Why → Solution

The problem: three copies of fetch

Without a plan, the three new functions get written as three separate copies of fetch. Each copy remembers the Authorization header, but one forgets Content-Type, so the server receives the body labelled as plain text and answers with an error that mentions nothing about headers. The delete function calls res.json() on a 204 response that has no body, so a successful delete throws and looks like a failure.

And when validation fails, the learner only sees a status number. Which field was wrong? Nobody knows, because the details sat in a response body that the copied code never read.

draft.js
// Three copies of fetch: the bugs hide in the details
async function createUser(name, email) {
  const res = await fetch(`${BASE}/users`, {
    method: "POST",
    headers: { Authorization: `Bearer ${TOKEN}` }, // no Content-Type
    body: JSON.stringify({ name, email }),
  });
  return res.json();
}

async function deleteUser(id) {
  const res = await fetch(`${BASE}/users/${id}`, { method: "DELETE", headers: AUTH });
  return res.json(); // 204 has no body, so this throws after a SUCCESSFUL delete
}

Why do the bugs hide in the details?

The mistakes are all in details that request() can own: the content type, the 204 rule and the error parsing. Centralising them shrinks each new function to one line and lets a single fix reach all of them.

Core concept: the body goes in, a status comes out

A write request has two halves that a read request does not. The request half is a body: you describe the new or changed data as JSON, serialise it with JSON.stringify and announce it with Content-Type: application/json. fetch will not guess for you. When you pass a string body it labels it text/plain, and a strict server rejects that. The response half is a status code that carries meaning beyond success: 201 means created, 204 means done with nothing to return, 404 means no such record, 409 means a conflict with existing data, and 422 means the data failed validation.

RequestBody sentAnswers you must handle
POST /usersJSON with the full new user201 with the created user, 409 duplicate email, 422 invalid fields
PATCH /users/:idJSON with only the changed fields200 with the updated user, 404 unknown id, 422 invalid fields
DELETE /users/:idNone204 with no body, 404 unknown id

1. Accept an optional body

request(method, route, body) adds Content-Type and calls JSON.stringify only when body is not undefined, so GET and DELETE keep sending no body at all.

2. Return null for 204

Check the status before parsing. A 204 response has no body by definition, and res.json() on an empty body throws a SyntaxError.

3. Keep the field details

A 422 body carries error.fields, for example { email: "invalid" }. ApiError stores it so the CLI can print email: invalid instead of only 422.

PATCH and PUT are not the same. PUT replaces the whole resource, so the client must send every field. PATCH sends only what changes. The CLI command update u_6 email=new@example.com is a partial change, so PATCH is the better fit. If an API offers only PUT, read the user first, merge your change and send the merged object back.

The command-line layer stays deliberately thin. runCommand(client, argv) receives the arguments after the script name (in a real program that is process.argv.slice(2)), chooses the client function by command name and returns the line to print. Returning a string instead of printing means the demo, and later tests, can check the result. One catch block turns an ApiError into 409 CONFLICT: Email already in use.

Mental model: body in, status out
  1. Describe the change as a JSON body
  2. request() adds Content-Type and sends
  3. Status decides: 2xx data, 4xx ApiError
  4. The CLI prints one readable line

Every write is the same round trip: data goes out as JSON, and the status tells you which of the four things happened: created, changed, removed or refused.

General pattern

javascript
async function request(method, route, body) {
  // headers; add Content-Type + JSON.stringify only when body !== undefined
  // 204 -> return null; !res.ok -> throw ApiError(status, code, message, { fields })
}

const create = async (input) => (await request("POST", "/things", input)).data;
const change = async (id, patch) => (await request("PATCH", `/things/${id}`, patch)).data;
const remove = async (id) => { await request("DELETE", `/things/${id}`); };

Teach request() once to take a body, handle 204 and keep error details. Each endpoint function then shrinks to one line that names a verb, a route and the data.

Part 2 code: write routes and a command-line layer

Here is the full Part 2 file. The mock API grew write routes with validation, so the client has something to talk to. Lines marked NEW, or placed between >>> NEW and <<< end, are what this part adds; everything else is Part 1 apart from request() gaining a body parameter. Run it and read the output top to bottom: it tries a duplicate, an invalid email, a delete of something already deleted and a malformed command on purpose.

part2.mjs
// user-cli, part 2: create / update / delete + a tiny command-line layer.
// Save as part2.mjs and run: node part2.mjs   (Node 20.12 or newer)
// Lines marked NEW (or between ">>> NEW" and "<<< end") were added in this part.
import http from "node:http";

// ===== 1. Mock API: now with write routes =====
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" },
];
let nextId = 6; // NEW

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

// >>> NEW in part 2: body parsing and validation for the mock
async function readJson(req) {
  let raw = "";
  for await (const chunk of req) raw += chunk;
  return raw ? JSON.parse(raw) : {}; // throws SyntaxError on malformed JSON
}
function validate(input, partial) {
  const fields = {};
  if (!partial || "name" in input) {
    if (typeof input.name !== "string" || !input.name.trim()) fields.name = "required";
  }
  if (!partial || "email" in input) {
    if (typeof input.email !== "string" || !/^[^@\s]+@[^@\s]+$/.test(input.email)) {
      fields.email = "invalid";
    }
  }
  return fields;
}
// <<< end of new mock helpers

const mock = http.createServer(async (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");
  const one = url.pathname.match(/^\/v1\/users\/([\w-]+)$/);
  const found = one && users.find((u) => u.id === one[1]);
  try {
    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 } });
    }
    // >>> NEW in part 2: POST /v1/users
    if (req.method === "POST" && url.pathname === "/v1/users") {
      const input = await readJson(req);
      const fields = validate(input, false);
      if (Object.keys(fields).length) {
        return fail(res, 422, "VALIDATION_ERROR", "Invalid user data", fields);
      }
      if (users.some((u) => u.email === input.email)) {
        return fail(res, 409, "CONFLICT", "Email already in use");
      }
      const user = { id: `u_${nextId++}`, name: input.name.trim(), email: input.email };
      users.push(user);
      return send(res, 201, { data: user });
    }
    // <<< end of POST
    if (one && !found) return fail(res, 404, "NOT_FOUND", `User ${one[1]} not found`);
    if (req.method === "GET" && found) return send(res, 200, { data: found });
    // >>> NEW in part 2: PATCH and DELETE /v1/users/:id
    if (req.method === "PATCH" && found) {
      const changes = await readJson(req);
      const fields = validate(changes, true);
      if (Object.keys(fields).length) {
        return fail(res, 422, "VALIDATION_ERROR", "Invalid user data", fields);
      }
      if (changes.name) found.name = changes.name.trim();
      if (changes.email) found.email = changes.email;
      return send(res, 200, { data: found });
    }
    if (req.method === "DELETE" && found) {
      users.splice(users.indexOf(found), 1);
      res.writeHead(204);
      return res.end(); // 204 No Content: no body at all
    }
    // <<< end of PATCH and DELETE
    fail(res, 404, "NOT_FOUND", "No such route");
  } catch (err) {
    if (err instanceof SyntaxError) {
      return fail(res, 400, "INVALID_JSON", "Body is not JSON");
    }
    fail(res, 500, "INTERNAL", "Unexpected server error");
  }
});

// ===== 2. The client library =====
class ApiError extends Error {
  constructor(status, code, message, extra = {}) { // NEW: extra
    super(message);
    this.name = "ApiError";
    this.status = status;
    this.code = code;
    this.fields = extra.fields; // NEW
  }
}

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, body) { // NEW: optional body
    const headers = { Authorization: `Bearer ${token}`, Accept: "application/json" };
    if (body !== undefined) headers["Content-Type"] = "application/json"; // NEW
    const res = await fetch(`${baseUrl}${route}`, {
      method,
      headers,
      body: body === undefined ? undefined : JSON.stringify(body), // NEW
    });
    if (res.status === 204) return null; // NEW: nothing to parse
    const payload = await res.json();
    if (!res.ok) {
      const { code, message, fields } = payload.error;
      throw new ApiError(res.status, code, message, { fields });
    }
    return payload;
  }
  const userPath = (id) => `/users/${encodeURIComponent(id)}`;
  return {
    listUsers({ page = 1, limit = 10 } = {}) {
      return request("GET", `/users?page=${page}&limit=${limit}`);
    },
    async getUser(id) {
      return (await request("GET", userPath(id))).data;
    },
    // >>> NEW in part 2
    async createUser(input) {
      return (await request("POST", "/users", input)).data;
    },
    async updateUser(id, changes) {
      return (await request("PATCH", userPath(id), changes)).data;
    },
    async deleteUser(id) {
      await request("DELETE", userPath(id));
    },
    // <<< end new
  };
}

// >>> NEW in part 2: the command-line layer (argv is process.argv.slice(2))
function parsePairs(pairs) {
  const changes = {};
  for (const pair of pairs) {
    const i = pair.indexOf("=");
    if (i < 1) throw new Error(`expected key=value, got "${pair}"`);
    changes[pair.slice(0, i)] = pair.slice(i + 1);
  }
  return changes;
}

const show = (u) => `${u.id}: ${u.name} <${u.email}>`;

function describeFields(fields) {
  if (!fields) return "";
  return ` (${Object.entries(fields).map(([k, v]) => `${k}: ${v}`).join(", ")})`;
}

async function runCommand(client, argv) {
  const [cmd, ...args] = argv;
  try {
    switch (cmd) {
      case "list": {
        const { data, meta } = await client.listUsers();
        return `${data.map((u) => u.name).join(", ")} (${meta.total} total)`;
      }
      case "get":
        return show(await client.getUser(args[0]));
      case "create": {
        const user = await client.createUser({ name: args[0], email: args[1] });
        return `created ${show(user)}`;
      }
      case "update": {
        const user = await client.updateUser(args[0], parsePairs(args.slice(1)));
        return `updated ${show(user)}`;
      }
      case "delete":
        await client.deleteUser(args[0]);
        return `deleted ${args[0]} (204)`;
      default:
        return `unknown command: ${cmd ?? "(none)"}`;
    }
  } catch (err) {
    if (!(err instanceof ApiError)) return `error: ${err.message}`;
    return `${err.status} ${err.code}: ${err.message}${describeFields(err.fields)}`;
  }
}
// <<< end of command-line layer

// ===== 3. Demo: pretend these arrays came from process.argv.slice(2) =====
await new Promise((resolve) => mock.listen(0, "127.0.0.1", resolve));
try {
  const { port } = mock.address();
  const env = { API_BASE_URL: `http://127.0.0.1:${port}/v1`, API_TOKEN: TOKEN };
  const client = createClient(loadConfig(env));
  const commands = [
    ["create", "Fiona", "fiona@example.com"],
    ["create", "Fiona", "fiona@example.com"],
    ["create", "Gus", "not-an-email"],
    ["update", "u_6", "email=fiona@work.example.com"],
    ["get", "u_6"],
    ["delete", "u_6"],
    ["get", "u_6"],
    ["delete", "u_6"],
    ["update", "u_1", "email"],
    ["list"],
  ];
  for (const argv of commands) {
    console.log(`$ user-cli ${argv.join(" ")}`);
    console.log(await runCommand(client, argv));
  }
} finally {
  mock.close();
}

Code breakdown

  1. Declare the body typeif (body !== undefined) headers["Content-Type"] = "application/json";

    The header is added only when there is a body. Without this line fetch would label the string body text/plain and the server would refuse it.

  2. Nothing to parse on 204if (res.status === 204) return null;

    A successful DELETE has no body. This line exits before parsing, so res.json() never throws on a delete that worked.

  3. Keep the field detailsthrow new ApiError(res.status, code, message, { fields });

    The error.fields of a 422 travel inside the ApiError. The CLI needs them to print email: invalid.

  4. PATCH sends only the changesreturn (await request("PATCH", userPath(id), changes)).data;

    updateUser() sends only the object of changed fields and returns the user the server answers with. It unwraps the { data } envelope here, so callers just see the user.

  5. Split on the first = onlyconst i = pair.indexOf("=");

    An argument like email=a=b contains two equals signs. Finding only the first one and keeping everything after it as the value stops the value from being cut.

  6. The mock enforces unique emailsif (users.some((u) => u.email === input.email)) {

    The mock refuses a repeated email with a 409, so the second create in the demo meets a real conflict and exercises the client's error path.

You should see
$ user-cli create Fiona fiona@example.com
created u_6: Fiona <fiona@example.com>
$ user-cli create Fiona fiona@example.com
409 CONFLICT: Email already in use
$ user-cli create Gus not-an-email
422 VALIDATION_ERROR: Invalid user data (email: invalid)
$ user-cli update u_6 email=fiona@work.example.com
updated u_6: Fiona <fiona@work.example.com>
$ user-cli get u_6
u_6: Fiona <fiona@work.example.com>
$ user-cli delete u_6
deleted u_6 (204)
$ user-cli get u_6
404 NOT_FOUND: User u_6 not found
$ user-cli delete u_6
404 NOT_FOUND: User u_6 not found
$ user-cli update u_1 email
error: expected key=value, got "email"
$ user-cli list
Alice, Bob, Chidi, Dara, Eli (5 total)

PUT, PATCH and repeating a request

Writes differ in what happens when the same request is sent twice, and that difference decides how a client may recover from a failure in Part 3. The demo shows it twice: the second create gets 409 only because the server enforces unique emails, and the second delete gets 404 because the first one worked.

MethodSent twiceWhat the demo shows
GETSame answer, nothing changesSafe to repeat any time
PUT, DELETESame end state; the status may differSecond delete: 404, but the user is gone either way
PATCHDepends on the changeSetting an email twice is harmless, adding 1 to a counter twice is not
POSTUsually creates a second recordSecond create: 409 only because the server checks emails

If your script only needs the user to be gone, a 404 on DELETE is a success in disguise. Treat it as one explicitly instead of ignoring errors.

Reading a 422 body and a 204 response

Validation errors are the one failure a person can fix, so they deserve readable output. The error body lists each bad field with a reason, and a few lines of code turn that into something a user can act on.

fields.mjs
// What a 422 body looks like, and how to turn it into lines a person can act on
const body = {
  error: {
    code: "VALIDATION_ERROR",
    message: "Invalid user data",
    fields: { email: "invalid", name: "required" },
  },
};

const lines = Object.entries(body.error.fields).map(([field, why]) => `${field}: ${why}`);
console.log(`${body.error.code} - ${body.error.message}`);
console.log(lines.join("\n"));

The other detail worth proving once is the empty 204. The Response below has a success status and no body, and trying to parse it as JSON fails, which is why request() checks the status first.

no-content.mjs
// 204 No Content is a success with no body, so there is nothing for json() to read
const res = new Response(null, { status: 204 });
console.log("status:", res.status, "| ok:", res.ok);
try {
  await res.json();
} catch (err) {
  console.log(`${err.name}: ${err.message}`);
}

In real projects

In real projects

Admin scripts and small CLIs like this one are how most teams first touch an API: import a CSV of customers, delete test data after a demo, rename a batch of accounts. The same three write functions sit behind a web form too, where error.fields lets the UI mark the exact input that failed instead of showing one generic banner.

Two habits carry over to production. Point destructive commands such as delete at a sandbox or staging environment first, because DELETE is the one request you cannot take back. And when a provider offers an idempotency key for POST requests, send one, since it makes a repeated create safe on the server instead of relying on the client to be careful.

Common mistakes

Common mistakes

Forgetting Content-Type on a JSON body

fetch labels a string body text/plain;charset=UTF-8, and a strict server answers 415 or ignores the body. Set Content-Type: application/json whenever you send JSON; request() does it for every call that has a body.

Calling res.json() on a 204

A successful delete answers with no body, so res.json() throws SyntaxError: Unexpected end of JSON input and a good result looks like a failure. Check the status before parsing.

Splitting key=value with split("=")

An argument such as url=https://x.example/?a=b contains two equals signs, and split would cut the value in half. Find the first = with indexOf and take everything after it as the value, and reject a pair that has no key.

Mini challenge

Make create safe to run twice

A script that creates the same user twice should not crash on the second run. Write ensureUser(client, input) that tries createUser, and when the server answers 409 looks the existing user up by email and returns it. Every other error, including a 422, must still reach the caller.

  • ensureUser returns { user, created: true } when the user is new
  • On an ApiError with status 409 it pages through listUsers to find the email and returns { user, created: false }
  • Any other error is rethrown unchanged, so a 422 is never hidden
  • Run it twice with one input and once with an invalid email, and print each outcome
ensure-user.mjs
// Make "create" safe to run twice.
// Assume createClient() from the lesson gives you client.createUser(input) and
// client.listUsers({ page, limit }), and that the ApiError class exists.

async function findByEmail(client, email) {
  // TODO 1: page through client.listUsers (limit 2) until you find the email
  // TODO 2: stop on an empty page or when page * limit >= meta.total; return null
}

async function ensureUser(client, input) {
  // TODO 3: try client.createUser(input) and return { user, created: true }
  // TODO 4: on ApiError status 409, call findByEmail and return { user, created: false }
  // TODO 5: rethrow every other error untouched (a 422 must NOT be swallowed)
}

// TODO 6: run ensureUser twice with the same input, plus once with a bad email,
//         and print what happened each time

Expected: Four lines: created=true for the first run, created=false for the second run and for an existing user, and a final line showing the 422 ApiError that was rethrown.

Show hint

Compare err.status inside the catch block, and remember that listUsers returns { data, meta }. Stop paging when a page is empty or page * limit reaches meta.total, otherwise a missing email would loop forever.

Show solution
ensure-user.mjs
import http from "node:http";

// ===== A minimal mock: unique emails, JSON in, JSON out =====
const users = [
  { id: "u_1", name: "Alice", email: "alice@example.com" },
  { id: "u_2", name: "Bob", email: "bob@example.com" },
];
const server = http.createServer(async (req, res) => {
  const url = new URL(req.url, "http://mock");
  const send = (status, body) => {
    res.writeHead(status, { "Content-Type": "application/json" });
    res.end(JSON.stringify(body));
  };
  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(200, { data, meta: { page, limit, total: users.length } });
  }
  if (req.method === "POST" && url.pathname === "/v1/users") {
    let raw = "";
    for await (const chunk of req) raw += chunk;
    const input = JSON.parse(raw);
    if (!input.email?.includes("@")) {
      return send(422, { error: { code: "VALIDATION_ERROR", message: "Invalid email" } });
    }
    if (users.some((u) => u.email === input.email)) {
      return send(409, { error: { code: "CONFLICT", message: "Email already in use" } });
    }
    const user = { id: `u_${users.length + 1}`, ...input };
    users.push(user);
    return send(201, { data: user });
  }
  send(404, { error: { code: "NOT_FOUND", message: "No such route" } });
});

// ===== A tiny client with the same ApiError shape as the project =====
class ApiError extends Error {
  constructor(status, code, message) {
    super(message);
    this.name = "ApiError";
    this.status = status;
    this.code = code;
  }
}

function createClient(baseUrl) {
  async function request(method, route, body) {
    const res = await fetch(`${baseUrl}${route}`, {
      method,
      headers: body ? { "Content-Type": "application/json" } : {},
      body: body && JSON.stringify(body),
    });
    const payload = await res.json();
    if (!res.ok) {
      const { code, message } = payload.error;
      throw new ApiError(res.status, code, message);
    }
    return payload;
  }
  return {
    createUser: async (input) => (await request("POST", "/users", input)).data,
    listUsers: ({ page = 1, limit = 10 } = {}) =>
      request("GET", `/users?page=${page}&limit=${limit}`),
  };
}

// ===== The challenge: make "create" safe to run twice =====
async function findByEmail(client, email) {
  for (let page = 1; ; page++) {
    const { data, meta } = await client.listUsers({ page, limit: 2 });
    const hit = data.find((u) => u.email === email);
    if (hit) return hit;
    if (data.length === 0 || page * 2 >= meta.total) return null;
  }
}

async function ensureUser(client, input) {
  try {
    return { user: await client.createUser(input), created: true };
  } catch (err) {
    if (!(err instanceof ApiError) || err.status !== 409) throw err;
    const existing = await findByEmail(client, input.email);
    if (!existing) throw err; // 409 but nobody found: do not hide a real conflict
    return { user: existing, created: false };
  }
}

await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
try {
  const client = createClient(`http://127.0.0.1:${server.address().port}/v1`);
  const chidi = { name: "Chidi", email: "chidi@example.com" };
  for (const [label, input] of [
    ["first run ", chidi],
    ["second run", chidi],
    ["old friend", { name: "Bob", email: "bob@example.com" }],
  ]) {
    const { user, created } = await ensureUser(client, input);
    console.log(`${label}: created=${created} ${user.id} ${user.name}`);
  }
  try {
    await ensureUser(client, { name: "Nobody", email: "not-an-email" });
  } catch (err) {
    console.log(`bad input : ${err.name} ${err.status} ${err.code} (rethrown)`);
  }
} finally {
  server.close();
}

Quick quiz 1 / 3

A server answers DELETE /users/u_6 with 204 No Content. What happens if the client calls res.json() on that response?

Quick quiz 2 / 3

You call fetch with method POST and body JSON.stringify({ name: "A" }) but no Content-Type header. Which Content-Type does fetch send?

Quick quiz 3 / 3

In the demo, the second delete u_6 prints 404 NOT_FOUND. What should a script that only needs the user gone conclude?

What to remember

  • Send JSON bodies with an explicit Content-Type: application/json; fetch labels a string body text/plain
  • Check for 204 before parsing, because a response with no body cannot be read with res.json()
  • Keep error.fields on ApiError so a 422 tells the user which input to fix
  • Use PATCH for partial changes, and remember that repeating POST can create a second record

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 2: Adding CRUD Features | Thuta Learning