Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 39 ยท Building an API

CRUD with an In-Memory Store

Implement a complete CRUD REST API for tasks with correct status codes, Location headers, PUT versus PATCH (JSON merge patch), 404s and a client that exercises every route.

CRUD stands for Create, Read, Update, Delete, the four things you do with almost any resource. In REST they map to HTTP methods: POST creates, GET reads, PUT and PATCH update, DELETE deletes. In this lesson you build a complete CRUD API for a tasks resource, with an in-memory Map as the "database" so you can focus on HTTP behavior. Later chapters swap the store for a real database without changing the API.

The contract

Operation Request Success Failure
List GET /tasks 200 + collection
Read one GET /tasks/:id 200 + task 404
Create POST /tasks + JSON 201 + task + Location 400 / 422
Replace PUT /tasks/:id + full JSON 200 + task 404 / 422
Modify PATCH /tasks/:id + partial JSON 200 + task 404 / 422
Delete DELETE /tasks/:id 204 404
stateDiagram-v2
    [*] --> Created: POST /tasks
    Created --> Created: PUT / PATCH
    Created --> [*]: DELETE

A resource's life: created, changed any number of times, deleted.

Write this table first, for every resource. It is your API design, and later you can turn it directly into documentation and tests.

The store

A tiny repository hides the storage. Handlers never touch the Map directly, so replacing it with SQL later changes only this class.

JavaScript
class TaskStore {
  #tasks = new Map();
  #next = 1;
  all() { return [...this.#tasks.values()]; }
  find(id) { return this.#tasks.get(id); }
  create(data) {
    const task = { id: String(this.#next++), done: false, ...data };
    this.#tasks.set(task.id, task);
    return task;
  }
  replace(id, data) {
    if (!this.#tasks.has(id)) return undefined;
    const task = { id, done: false, ...data };
    this.#tasks.set(id, task);
    return task;
  }
  update(id, changes) {
    const current = this.#tasks.get(id);
    if (!current) return undefined;
    const task = { ...current, ...changes, id };
    this.#tasks.set(id, task);
    return task;
  }
  remove(id) { return this.#tasks.delete(id); }
}

Two small but important details: the server controls id (a client cannot choose or change it with PUT or PATCH), and new tasks get defaults such as done: false.

PUT versus PATCH in code

  • PUT replaces the whole resource. Fields the client leaves out go back to their defaults (here, done is false again).
  • PATCH with JSON Merge Patch (RFC 7396) changes only the fields present. A key set to null removes that field.

The helper that applies a merge patch is short:

JavaScript
function mergePatch(target, patch) {
  const result = { ...target };
  for (const [key, value] of Object.entries(patch)) {
    if (value === null) delete result[key];
    else result[key] = value;
  }
  return result;
}

(The version here handles flat objects; the full RFC also merges nested objects recursively.)

The complete API

The program below combines the store, the merge patch and the routes. It then drives the whole API with a client script: create, list, read, replace, patch, delete and the failures. Read the output top to bottom as a conversation.

Node.js A complete CRUD API for tasks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

What to notice in the output:

  • POST returns 201 and a Location header, and the body contains the server-assigned id.
  • PATCH { done: true } changed one field; the later PUT with only a title reset done to false. That is the replace-versus-modify difference.
  • PATCH { note: null } removed the note field entirely (merge patch).
  • The second DELETE returned 404: same final state, different response, which is what idempotent means.
  • The id in a PUT body is ignored; the URL decides which resource it is.

Conditional updates against lost updates

Two users read task 1, both edit and both PUT. The second PUT silently overwrites the first. The fix from headers is optimistic concurrency: send a version in ETag, require If-Match on updates and answer 412 Precondition Failed (or 409) on a mismatch. A simple version counter works as the ETag:

Node.js Optimistic concurrency with a version

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Design checklist for every CRUD resource

  • Does POST return 201, the new representation and Location?
  • Does a missing resource return 404 for read, replace, patch and delete?
  • Are server-owned fields (id, timestamps) protected from client changes?
  • Does PUT have clear replace semantics and PATCH clear merge semantics?
  • Is invalid input rejected with a precise 400 or 422? Next lesson: validation.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A client PUTs {"title": "X"} to /tasks/1 which previously had done true. What should done be afterwards under replace semantics?

    PUT supplies the complete new state. Missing fields return to defaults, unlike PATCH.
  2. 2. What does a merge patch of {"note": null} do?

    In JSON Merge Patch (RFC 7396), null means "remove this key".
  3. 3. Why must a client not be able to change id via PUT or PATCH?

    Server-owned fields (id, timestamps) are set by the server; ignore or reject client values for them.
  4. 4. Two users edit the same record. What technique prevents the second save from silently overwriting the first?

    Requiring the version the client last saw lets the server reject stale updates with 412.

Summary

  • CRUD maps to POST, GET, PUT/PATCH and DELETE; write the contract table before the code.
  • Return 201 + Location on creation, 204 on delete and 404 when an item does not exist.
  • PUT replaces (missing fields reset); PATCH with merge patch changes only the present fields and null removes one.
  • Servers own ids and timestamps; hide storage behind a repository.
  • Use a version number or ETag with If-Match to stop lost updates.

Next: Validation and Input Handling