Phase 2 · Web Servers & HTTP APIsModule 12~62 min read

REST API Design & CRUD

Design predictable resource-oriented endpoints with correct methods, statuses, validation, filtering, pagination, and CRUD behavior.

What you'll learn

REST APIs are contracts around resources and HTTP semantics, not collections of arbitrary URLs. You will design predictable CRUD endpoints, validation errors, filters, pagination, and conflict behavior.

By the end of this lesson, you'll be able to:

  • Model endpoints around resource nouns
  • Map CRUD outcomes to appropriate methods and statuses
  • Validate create and update payloads
  • Design bounded filtering and pagination

Core mental model

Node.js becomes easier when you separate the JavaScript language from the runtime and the operating-system capabilities it exposes. Use this table as a decision guide.

ConceptWhat it meansDecision rule
ResourceA domain concept with an address and representationsUse stable plural nouns such as /tasks
Method semanticsGET reads, POST creates, PUT replaces, PATCH changes, DELETE removesHonor safety and idempotency expectations
Status codeMachine-readable summary of the outcomeUse the most specific standard code and a consistent body
PaginationA bounded window over a collectionCap page size and return navigation metadata

Professional workflow

Build and verify Node.js programs from the terminal in small, observable steps.

  1. Name resources and identifiers
  2. Write a route/status matrix
  3. Define request and response representations
  4. Validate syntax, shape, and domain rules
  5. Implement service operations independent of Express
  6. Add filters and capped pagination
  7. Document conflict, not-found, and invalid-input behavior

Keep the feedback loop short

Run the smallest useful command after every meaningful change. Read the complete error message before editing again, and keep inputs and outputs visible while you learn.

Guided code lab

Define a predictable route matrix

The same resource noun supports collection and item operations; methods carry the action.

api-contract.txt
GET    /api/tasks          200  list tasks
POST   /api/tasks          201  create a task
GET    /api/tasks/:id      200  retrieve one task
PATCH  /api/tasks/:id      200  update selected fields
DELETE /api/tasks/:id      204  remove a task

Common failures: 400 malformed, 404 missing, 409 conflict, 422 invalid fields

Create a resource and identify its location

A successful POST returns 201, the representation, and a Location header pointing at the new resource.

tasks-router.js
router.post("/", (request, response) => {
  const input = validateNewTask(request.body);
  const task = taskService.create(input);

  response
    .status(201)
    .location("/api/tasks/" + task.id)
    .json({ data: task });
});

router.delete("/:taskId", (request, response) => {
  taskService.remove(request.params.taskId);
  response.status(204).end();
});

Bound collection queries

The server normalizes and caps user input before querying. Metadata lets clients build navigation without guessing.

pagination.js
export function parseListQuery(query) {
  const page = Math.max(1, Number.parseInt(query.page ?? "1", 10) || 1);
  const requested = Number.parseInt(query.limit ?? "20", 10) || 20;
  const limit = Math.min(100, Math.max(1, requested));
  const completed = query.completed === undefined
    ? undefined
    : query.completed === "true";

  return { page, limit, completed, offset: (page - 1) * limit };
}

Production practice

Stay consistent

Use one envelope, error shape, date format, identifier style, and pagination model across resources.

Preserve semantics

GET must not change server state; retries of PUT and DELETE should have predictable idempotent effects.

Bound collections

Never allow an untrusted query to request an unlimited data set or arbitrary expensive sort.

Common failure mode

Returning 200 for every outcome forces clients to parse prose to discover failure. Use HTTP statuses for the outcome and JSON for details.

Independent workshop

Design and implement a complete in-memory project API with CRUD, filters, and pagination.

Your finished workshop must include:

  • A route/status contract table
  • Validation for create and patch
  • Location on creation and 204 on deletion
  • Capped page sizes and metadata
  • Consistent not-found, conflict, and validation errors

Definition of done

Run the happy path and at least two edge cases, keep responsibilities separated, and add a short README explaining how to run the program.

Recap & quick check

Key takeaways

  • Resources are nouns with representations
  • Methods carry operation semantics
  • Statuses communicate outcomes
  • 201 creation should identify the new resource
  • Validation errors are client-facing contracts
  • Pagination must be bounded

Quick check

1. Which method normally creates a collection member?

2. Which status fits successful creation?

3. Which method is intended for a partial update?

4. Why cap page size?

Next: Middleware, Validation & Composition