Chuyển đến nội dung

Bài 12 · Building an API

Building a Router

Replace if-chains with a route table: path parameters, method matching, automatic 404 and 405 with Allow headers, route groups and a reusable mini router in Node.js.

Routing means choosing the right piece of code for each request, based on the method and the path. An if (url === '/books' && method === 'GET') chain works for a demo, but real APIs have dozens of routes with parameters (/books/:id), and need consistent 404 and 405 answers. A router is the table and the matching logic that makes that manageable.

In this lesson you build a small, reusable router, and the rest of the course uses the same idea whether you work in Express, Fastify, Laravel or Django.

What a router does

  1. Stores routes: a method, a path pattern with named parameters, and a handler.
  2. Matches an incoming request and extracts the parameters (/books/42 gives { id: '42' }).
  3. Answers failures uniformly: 404 when no pattern matches the path, 405 plus an Allow header when the path matches but the method does not.
  4. Calls the handler with a small context object, and turns its return value into a response.
flowchart LR
    A["Request GET /books/42"] --> B["Match patterns"]
    B --> C{"Path matches?"}
    C -- No --> D["404"]
    C -- Yes --> E{"Method matches?"}
    E -- No --> F["405 + Allow"]
    E -- Yes --> G["Handler(ctx)"]
    G --> H["Response"]

The router sits between the raw request and your handlers.

Path patterns with parameters

A pattern like /authors/:authorId/books/:id has two kinds of segments: literal (authors, books) and parameters (:authorId, :id). The easiest implementation turns each pattern into a regular expression with named groups, which is what most frameworks do internally.

Rules worth following:

  • Match the whole path (anchor with ^ and $).
  • Decode each parameter with decodeURIComponent, and catch malformed escapes (%E0%A4%A) so they become 400, not a crash.
  • Order matters when patterns overlap: /books/search and /books/:id. Register literal routes before parameterised ones, or let the router prefer literal segments.

A reusable mini router

The class below supports get, post, put, patch and delete, route groups with a prefix and the two automatic error answers. Handlers receive { req, params, query, body } and return { status, body, headers }, or just a value (treated as 200). Keep the code in your head; later lessons reuse it.

Node.js A mini router with 404 and 405

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.

The output shows all outcomes: parameters extracted (42, the hobbit after decoding), 405 with Allow: GET, POST for DELETE /books, 400 for a malformed escape and 404 for an unknown path.

Route groups and versioned prefixes

router.group('/books', ...) repeats a prefix once. Groups are also where you would attach things shared by several routes: an authentication requirement, a version prefix such as /v1 or a rate limit. Real frameworks let you write Route::prefix('v1')->middleware('auth')->group(...) for exactly this.

Handler design: return values, not res

Notice that the handlers above never touch res. They receive a context and return a description of the answer. That has two payoffs:

  • Handlers become plain functions you can test without any HTTP at all (call handler({ params: { id: '42' } }) and compare the result).
  • The one place that writes responses can add consistent headers, logging, error handling and serialisation. The middleware lesson builds on this.
Node.js Handlers are plain functions: test without HTTP

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.

Trailing slashes, case and normalisation

Decide how strictly to match. Most APIs treat /books/ as the same as /books by redirecting or normalising, or reject the slashed form with 404 to keep one canonical URL. Paths are case-sensitive by default; do not lowercase them silently because ids can be case-sensitive. Document the rule and test it.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. When should a router answer 405 instead of 404?

    405 Method Not Allowed means the resource exists but does not support this method; include an Allow header.
  2. 2. Why decode path parameters with decodeURIComponent inside a try/catch?

    Clients send percent-encoded values, and a broken escape such as %E0%A4%A would otherwise crash the handler.
  3. 3. Why are handlers that return a result object easier to test than ones that write to res?

    A pure function can be called directly in a unit test with plain objects.
  4. 4. With routes /books/search and /books/:id, what can go wrong if :id is registered first?

    Literal routes must be matched before parameterised ones, or the parameter pattern swallows them.

Summary

  • A router matches method plus path against a route table and extracts named parameters.
  • It answers 404 for unknown paths and 405 with Allow for known paths with the wrong method.
  • Decode parameters safely and register literal routes before parameterised ones.
  • Groups share prefixes (and later middleware) for versions or protected areas.
  • Handlers that return { status, body } stay testable and keep response writing in one place.

Next: CRUD with an In-Memory Store

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.