Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 37 ยท Projects and Practice

Project: A To-Do REST API with Auth and Pagination

Build a complete REST API in Deno with Deno KV. Add API-key middleware, validation, filtering, cursor pagination and optimistic concurrency with ETag and If-Match, then test it without a server.

A to-do list is the classic exercise because it contains every part of a real API in a small space: create, read, update and delete (CRUD), validation, ownership, filtering, paging through results, and the question of what happens when two clients edit the same item. This project builds all of that on top of Deno KV, a hand-made router and middleware, and the request and response habits from Requests and Responses.

By the end you will have a design you can reuse for any resource: notes, bookmarks, tickets, products.

The code runs here with MiniKv (the in-memory stand-in for Deno KV) on Node 24. In real Deno you pass await Deno.openKv() to createApp and give the result to Deno.serve. Everything else is identical.

The API

Request Result
POST /todos { "title": "..." } 201 and the new to-do
GET /todos?done=true&limit=2&cursor=... a page of your to-dos, newest first
GET /todos/:id one to-do, with an ETag header
PATCH /todos/:id { "title"?, "done"? } update; honors If-Match
DELETE /todos/:id 204

All routes need an Authorization: Bearer <api-key> header. Each key belongs to one user, and users can only see their own to-dos. Without a valid key the answer is 401.

KV layout

TEXT
["todos", userId, id]   -> { id, title, done, createdAt, updatedAt }

Putting userId in the key does two jobs: it isolates users (a prefix list of ["todos", userId] can never include another user's data), and it keeps one user's to-dos adjacent for fast listing. The id is a time-ordered string, so listing in reverse gives newest first.

Design decisions

  1. Authentication middleware looks up the key and attaches the user to the request context. The route handlers never parse headers themselves.
  2. Validation returns all problems at once (422), so a client fixes them in one go.
  3. Pagination uses KV cursors, never offsets. The server returns nextCursor, the client sends it back.
  4. Concurrency control: every to-do read returns an ETag equal to its versionstamp. PATCH with If-Match: <etag> succeeds only if nobody changed the item since. Otherwise it answers 412 Precondition Failed, and the client reloads. Without the header the update is last-write-wins.

The implementation

Node.js The complete to-do API

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.

Reading the output

The run demonstrates each rule:

  • 401 without a key, and Grace's key cannot read Ada's 0001 (it answers 404, not 403, so it does not even reveal that the id exists).
  • 422 lists every invalid field at once.
  • The first PATCH with the current ETag succeeds and returns a new one. The second reuses the old ETag and gets 412: someone (here, the first patch) changed the item in between. This prevents the "lost update" where an old form overwrites newer data.
  • Filtering with ?done=true and paging with ?limit=2 return nextCursor while more data may follow.

Pagination in practice

Each request reads one page of limit entries and then filters it, so with ?done=true a page can hold fewer than limit items while nextCursor still points to more. That is simple and fine for personal lists. If you need full pages of filtered results, maintain a second index such as ["todos_done", user, id] so that filtering becomes a prefix list instead of a scan of everything. Remember the trade-off from Deno KV Basics: KV answers key lookups quickly, so you design keys for the questions you will ask.

A client pages like this:

TypeScript
let cursor: string | null = null;
do {
  const url = new URL("https://api.example.com/todos");
  url.searchParams.set("limit", "20");
  if (cursor) url.searchParams.set("cursor", cursor);
  const page = await (await fetch(url, { headers: { authorization: `Bearer ${key}` } })).json();
  render(page.items);
  cursor = page.nextCursor;
} while (cursor);

Security checklist for this API

  • Compare API keys in constant time if you store them as secrets; better, store only a hash of each key.
  • Rate-limit by user (a sum counter keyed by user and minute).
  • Cap body sizes and string lengths (done for titles).
  • Return the same error shape everywhere, and never leak stack traces.
  • Add CORS headers only for the origins that need them (see Requests and Responses).
  • Test the unhappy paths as hard as the happy ones.

Testing the API

TypeScript
import { assertEquals } from "jsr:@std/assert";
import { createApp } from "./app.ts";

function setup() {
  let n = 0;
  return Deno.openKv(":memory:").then((kv) => ({
    kv,
    app: createApp(kv, { apiKeys: { k1: "ada" }, newId: () => String(++n) }),
  }));
}

const authed = (path: string, init: RequestInit = {}) =>
  new Request("http://x" + path, {
    ...init,
    headers: { authorization: "Bearer k1", ...init.headers },
  });

Deno.test("rejects missing API key", async () => {
  const { app, kv } = await setup();
  const res = await app(new Request("http://x/todos"));
  assertEquals(res.status, 401);
  await res.body?.cancel();
  kv.close();
});

Deno.test("stale If-Match gets 412", async () => {
  const { app, kv } = await setup();
  await (await app(authed("/todos", { method: "POST", body: '{"title":"a"}' }))).body?.cancel();
  const first = await app(authed("/todos/1"));
  const etag = first.headers.get("etag")!;
  await first.body?.cancel();

  await (await app(authed("/todos/1", { method: "PATCH", body: '{"done":true}' }))).body?.cancel();
  const stale = await app(authed("/todos/1", {
    method: "PATCH",
    body: '{"title":"x"}',
    headers: { "if-match": etag },
  }));
  assertEquals(stale.status, 412);
  await stale.body?.cancel();
  kv.close();
});

Notice res.body?.cancel(): Deno's resource sanitizer fails a test that leaves a response body unread.

Ideas to extend it

  • Add due dates and sort by them with a second index.
  • Add tags and a GET /tags endpoint that counts with sum.
  • Stream changes to a browser with SSE and kv.watch.
  • Generate an OpenAPI document from the route table.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is the userId part of the KV key?

    Listing the prefix ["todos", userId] can only return that user's data, which is a simple and strong isolation boundary.
  2. 2. What does a 412 Precondition Failed answer to a PATCH with If-Match mean?

    If-Match carries the ETag the client saw. A mismatch shows a newer version exists, so the edit would overwrite it.
  3. 3. Why use a cursor instead of page numbers?

    Offsets drift when data changes between requests. A cursor remembers where the last page ended.
  4. 4. Why does the API answer 404 instead of 403 for another user's to-do?

    Since lookups are scoped to the caller's own prefix, other users' items simply do not exist from their point of view.

Summary

  • Scope data by user in the key, authenticate in middleware and keep handlers free of header parsing.
  • Validate and report every error at once (422); filter and page with limits and cursors.
  • Use ETags with If-Match for optimistic concurrency, and atomic().check(entry) for the final write.
  • Test by calling the handler with new Request, including the failure paths.

Next: Project: A Real-Time Chat