JS-290 · Lesson 6 of 12 · 27 min

Building the API

▶ Video coming soon A video version of this lesson is on the way.

By Tuesday, April 10, the tables exist on every laptop and on staging, Theo's token endpoint works, and Mira starts on the part of the service that every screen will depend on: the HTTP API. She writes the API description first and the code second, the order Theo insisted on when he designed the Food Hub's /api/v1 contract in JS-120. A written contract lets Odalys build screens against it in parallel, lets Tavish write tests before the handlers exist, and lets everyone argue about names before the names are in a database.

The rescue API copies the conventions of the partner order service, so that anyone who has worked on one can work on the other. It lives under /api/rescue/v1. It returns JSON, and errors as problem details in the format of RFC 9457. Lists use cursor pagination with a default page of 25 and a maximum of 100. Requests that create something carry an Idempotency-Key header. Every request is authenticated, every object is checked against the caller's identity, and anything the caller may not see is reported as not found.

The resources and their endpoints

Mira starts from the story map and asks, for each story, what a screen needs to send and receive. The result is a short list of resources, offers, runs, receipts and reports, with the operations each story needs. Actions that change a run's status are written as small sub-resources, such as POST /runs/{id}/pickup, rather than as a general PATCH of the status field, because each action has its own rules, its own role and its own body.

The Rescue Runs API, version 1
Method and pathWhoWhat it does
GET /offers?status=open&area=north-endDriverOpen offers, sorted by distance from the area
POST /offersDonor staffPost an offer; needs Idempotency-Key
POST /offers/{id}/withdrawDonor staffWithdraw an offer that has not been picked up
POST /offers/{id}/claimDriverClaim an offer, creating a run; applies the claiming rules
POST /runs/{id}/releaseDriverGive a claimed run back so someone else can take it
POST /runs/{id}/pickupDriverMark the food collected; accepts an offline timestamp
POST /runs/{id}/receiptReceiverRecord weight and, for chilled food, temperature
GET /me/runsDriverThe caller's own runs, newest first
GET /runs?status=claimed&date=2029-04-24CoordinatorLucy's view of runs by day and status
GET /reports/monthly?month=2029-04CoordinatorTotals by donor and category for a month
A request travelling left to right through the service: Theo's web server with HTTPS, then middleware for request id and logging, body size limit, authentication, rate limit, then the route handler, which validates input with a schema, calls the claims service, and maps any error to a problem details response. The claims service calls the repository, which calls PostgreSQL.
What happens to a request

Validating input with a schema

Every value in a request body crosses a trust boundary, so every body is checked against a schema before any rule sees it. The studio uses zod 4, as the partner service does. A schema says what shape the data must have, which fields are required, their types, their ranges and their formats. If the body does not match, the handler returns 422 with a list of field errors in the same shape the portal's forms already understand. The service also refuses fields it does not know, because an unexpected field is either a client bug or someone probing.

JavaScript Example · offer-schema.mjs
import { z } from 'zod';

const Offer = z.strictObject({
  locationId: z.number().int().positive(),
  category: z.enum(['bakery', 'produce', 'prepared', 'dairy', 'dry', 'other']),
  estKg: z.number().min(0.5).max(500),
  chilled: z.boolean(),
  windowStart: z.iso.datetime({ offset: true }),
  windowEnd: z.iso.datetime({ offset: true }),
  note: z.string().max(300).default(''),
}).refine((o) => Date.parse(o.windowEnd) > Date.parse(o.windowStart), {
  message: 'must be after the start', path: ['windowEnd'],
});

function check(body) {
  const r = Offer.safeParse(body);
  if (r.success) return { ok: true, value: r.data };
  return { ok: false, errors: r.error.issues.map((i) => ({ field: i.path.join('.') || '(body)', message: i.message })) };
}

console.log(check({ locationId: 3, category: 'bakery', estKg: 12, chilled: false,
  windowStart: '2029-04-24T17:00:00-04:00', windowEnd: '2029-04-24T18:00:00-04:00' }));
console.log(JSON.stringify(check({ locationId: 3, category: 'cake', estKg: 0.2, chilled: 'no',
  windowStart: '2029-04-24T17:00:00-04:00', windowEnd: '2029-04-24T18:00:00-04:00', price: 5 }), null, 1));
console.log(check({ locationId: 3, category: 'dairy', estKg: 8, chilled: true,
  windowStart: '2029-04-24T17:00:00-04:00', windowEnd: '2029-04-24T16:00:00-04:00' }).errors);

What this code does

The strict object schema lists every allowed field with its type and limits, and refuses fields it does not know, such as price. A refine step checks a rule that involves two fields, that the window ends after it starts, and attaches its message to the windowEnd field; it runs only once every field is valid, which is why the last example shows it on its own. The check function turns zod's issues into the list of field and message pairs the screens already display.

Running it
$ node offer-schema.mjs
{
  ok: true,
  value: {
    locationId: 3,
    category: 'bakery',
    estKg: 12,
    chilled: false,
    windowStart: '2029-04-24T17:00:00-04:00',
    windowEnd: '2029-04-24T18:00:00-04:00',
    note: ''
  }
}
{
 "ok": false,
 "errors": [
  {
   "field": "category",
   "message": "Invalid option: expected one of \"bakery\"|\"produce\"|\"prepared\"|\"dairy\"|\"dry\"|\"other\""
  },
  {
   "field": "estKg",
   "message": "Too small: expected number to be >=0.5"
  },
  {
   "field": "chilled",
   "message": "Invalid input: expected boolean, received string"
  },
  {
   "field": "(body)",
   "message": "Unrecognized key: \"price\""
  }
 ]
}
[ { field: 'windowEnd', message: 'must be after the start' } ]

Two details in the schema come from earlier lessons. The weight is accepted in kilograms with a minimum of 0.5 because that is what the Canadian form asks for; the US form sends pounds to a separate field, and the handler converts either to grams before the service sees it, so the rule *store one unit* holds. And the note is limited to 300 characters because the driver's screen shows it in full, which is the same limit the kitchen board uses for agency notes.

Thin handlers, rules in services

Following the dependency rule from lesson 3, a route handler does four things and nothing else: it reads and validates the request, it identifies the caller, it calls one service function, and it turns the result into an HTTP response. Business rules, such as *a driver without a cooler cannot claim chilled food*, live in the claims service, where they can be tested without HTTP. The team writes handlers as plain functions that take a simple request object and return a simple response object, and wires them into Express in one place. That makes the handlers runnable in tests, and in this lesson's examples, without starting a server.

JavaScript Example · Mapping service errors to problem details
// Service errors carry a kind; the handler maps kinds to problem details.
class RuleError extends Error {
  constructor(kind, detail) { super(detail); this.kind = kind; }
}
const statusFor = { invalid: 422, not_found: 404, conflict: 409, forbidden: 403 };
const titleFor = {
  invalid: 'Request body is not valid', not_found: 'Not found',
  conflict: 'The request conflicts with a rule', forbidden: 'Not allowed',
};

function toProblem(err, instance) {
  if (!(err instanceof RuleError)) {
    return { status: 500, body: { type: 'about:blank', title: 'Internal error', status: 500, instance } };
  }
  const status = statusFor[err.kind];
  return { status, body: { type: `https://riverside-food-hub.example/problems/${err.kind}`, title: titleFor[err.kind], status, detail: err.message, instance } };
}

console.log(toProblem(new RuleError('conflict', 'This run overlaps another of your runs.'), '/api/rescue/v1/offers/41/claim'));
console.log(toProblem(new Error('connection reset'), '/api/rescue/v1/me/runs').body);
Output
{ status: 409, body: { type: "https://riverside-food-hub.example/problems/conflict", title: "The request conflicts with a rule", status: 409, detail: "This run overlaps another of your runs.", instance: "/api/rescue/v1/offers/41/claim" } }
{ type: "about:blank", title: "Internal error", status: 500, instance: "/api/rescue/v1/me/runs" }

What this code does

A RuleError carries a kind such as conflict, and the mapping turns each kind into an HTTP status and a short title. Problem details follow RFC 9457, with a type link, a title, the status, a human-readable detail and the path of the request. Any other error becomes a plain 500 with no detail, so an internal message such as a database error never reaches the client.

The last line of that example matters for security. When something unexpected fails, the client gets *Internal error* and a request id, while the full error and stack trace go to the structured logs set up in JS-260. WEB-230's finding F2, detailed error pages on Theo's staging server, is exactly what this avoids.

Object-level authorization

Authentication says who the caller is; authorization says what they may do to *this* object. The partner service learned in JS-240 that checking roles is not enough: an agency that may read orders may still only read its own. Rescue Runs has the same shape. A driver may release only their own runs. Donor staff may withdraw only their own donor's offers. A receiver may record a receipt only for a run that has been picked up. For each request the service loads the object with the caller's identity in the query, and if nothing comes back, it returns 404, exactly as if the object did not exist. Returning 403 would tell a curious caller that the id is real.

JavaScript Example · A thin handler
// A claim handler: validate, identify, call the service, map the result.
const offers = new Map([
  [41, { id: 41, donor: 'copperleaf', chilled: true, status: 'open', date: '2029-04-24', start: '17:00', end: '18:00' }],
  [42, { id: 42, donor: 'pine-hill', chilled: false, status: 'claimed', date: '2029-04-24', start: '18:00', end: '18:30' }],
]);
const myRuns = { wendy: [], ilse: [] };

function claimService(driver, offerId) {
  const offer = offers.get(offerId);
  if (!offer) return { error: 'not_found', detail: 'No such offer.' };
  if (offer.status !== 'open') return { error: 'conflict', detail: 'Someone has already claimed this offer.' };
  if (offer.chilled && !driver.cooler) return { error: 'conflict', detail: 'Chilled food needs a driver with a cooler.' };
  offer.status = 'claimed';
  const run = { id: 900 + offerId, offerId, driver: driver.id };
  myRuns[driver.id].push(run);
  return { run };
}

function handleClaim(req) {
  if (!req.user || req.user.role !== 'driver') return { status: 401 };
  const id = Number(req.params.id);
  if (!Number.isInteger(id) || id <= 0) return { status: 404 };
  const r = claimService(req.user, id);
  if (r.error === 'not_found') return { status: 404 };
  if (r.error) return { status: 409, detail: r.detail };
  return { status: 201, location: `/api/rescue/v1/runs/${r.run.id}` };
}

console.log(handleClaim({ params: { id: '41' }, user: { id: 'ilse', role: 'driver', cooler: false } }));
console.log(handleClaim({ params: { id: '41' }, user: { id: 'wendy', role: 'driver', cooler: true } }));
console.log(handleClaim({ params: { id: '42' }, user: { id: 'wendy', role: 'driver', cooler: true } }));
console.log(handleClaim({ params: { id: 'abc' }, user: { id: 'wendy', role: 'driver', cooler: true } }));
console.log(handleClaim({ params: { id: '41' } }));
Output
{ status: 409, detail: "Chilled food needs a driver with a cooler." }
{ status: 201, location: "/api/rescue/v1/runs/941" }
{ status: 409, detail: "Someone has already claimed this offer." }
{ status: 404 }
{ status: 401 }

What this code does

The handler checks that there is a signed-in driver, turns the path parameter into a positive whole number, calls the service once and maps its answer to a status. A successful claim returns 201 with a Location header pointing at the new run, while rule failures return 409 with the service's explanation. An id that is not a number gets the same 404 as an id that does not exist, so the response never reveals more than it must.

Safe retries with idempotency keys

Drivers use the app on phones in loading bays and car parks, where connections drop. A phone that sends *mark this run picked up* and loses the reply does not know whether the server received it, so it sends it again. For actions that are safe to repeat, such as marking a pickup, the service simply accepts the second request. For actions that create something, such as posting an offer, a repeat would create a duplicate. The answer, used across the studio's services since JS-120, is the Idempotency-Key header: the client sends a random key with the request, and the server remembers the response it gave for that key for 24 hours. A repeat with the same key gets the same response, and nothing is created twice.

JavaScript Example · Idempotency keys in miniature
// Remember responses by idempotency key for 24 hours.
const DAY = 24 * 60 * 60 * 1000;
function idempotent(store, now) {
  return (key, bodyHash, run) => {
    const seen = store.get(key);
    if (seen && now() - seen.at < DAY) {
      if (seen.bodyHash !== bodyHash) return { status: 422, detail: 'Key reused with a different body.' };
      return { ...seen.response, replayed: true };
    }
    const response = run();
    store.set(key, { at: now(), bodyHash, response });
    return response;
  };
}

let clock = Date.UTC(2029, 3, 24, 21, 0);
let created = 0;
const post = idempotent(new Map(), () => clock);
const create = () => ({ status: 201, id: ++created });

console.log(post('k-7f3a', 'h1', create));
console.log(post('k-7f3a', 'h1', create));
console.log(post('k-7f3a', 'h2', create));
clock += DAY + 1;
console.log(post('k-7f3a', 'h1', create));
console.log('offers created:', created);
Output
{ status: 201, id: 1 }
{ status: 201, id: 1, replayed: true }
{ status: 422, detail: "Key reused with a different body." }
{ status: 201, id: 2 }
offers created: 2

What this code does

The store maps each key to the time it was first seen, a hash of the request body and the response that was sent. A repeat within 24 hours with the same body gets the stored response, marked as replayed, and a repeat with a different body is refused because it means the client made a mistake. After 24 hours the key is forgotten, which is why the last request creates a second offer.

Wiring it into Express

With the handlers written as plain functions, the Express part is short. One router mounts the handlers under the version prefix. Middleware handles the concerns every request shares, in a fixed order: a request id, a body size limit of 64 KB, authentication from the portal token or the donor session, the rate limits copied from the partner service, and finally one error handler that turns anything unexpected into a 500 problem. Express 5 passes rejected promises from async handlers to the error handler automatically, which removes a whole class of forgotten try and catch blocks.

JavaScript Example · services/rescue-runs/src/app.js
// src/app.js
import express from 'express';
import { requestId, authenticate, rateLimit, adapt } from './http/middleware.js';
import * as offers from './routes/offers.js';
import * as runs from './routes/runs.js';
import * as reports from './routes/reports.js';
import { problemHandler } from './http/problems.js';

export function createApp(deps) {
  const app = express();
  app.disable('x-powered-by');
  app.use(requestId(), express.json({ limit: '64kb' }));
  app.get('/healthz', (req, res) => res.json({ ok: true }));
  app.get('/healthz/ready', adapt(deps.ready));

  const v1 = express.Router();
  v1.use(authenticate(deps.auth), rateLimit(deps.limits));
  v1.get('/offers', adapt(offers.list(deps)));
  v1.post('/offers', adapt(offers.create(deps)));
  v1.post('/offers/:id/withdraw', adapt(offers.withdraw(deps)));
  v1.post('/offers/:id/claim', adapt(offers.claim(deps)));
  v1.post('/runs/:id/release', adapt(runs.release(deps)));
  v1.post('/runs/:id/pickup', adapt(runs.pickup(deps)));
  v1.post('/runs/:id/receipt', adapt(runs.receipt(deps)));
  v1.get('/me/runs', adapt(runs.mine(deps)));
  v1.get('/runs', adapt(runs.byDay(deps)));
  v1.get('/reports/monthly', adapt(reports.monthly(deps)));
  app.use('/api/rescue/v1', v1);

  app.use(problemHandler(deps.log));
  return app;
}

What this code does

The app factory takes its dependencies, such as repositories, the token checker and the logger, as one object, so tests can pass in-memory versions. Shared middleware runs in a fixed order before any handler, and each plain handler is wrapped by an adapt function that turns Express's request into the simple object the handlers expect. The final problem handler catches anything unexpected, logs it with the request id and returns a 500 problem without internal details.

Creating the app from a function, instead of at the top of a module, is a habit from JS-230. It means the integration tests in lesson 8 can build an app with an in-memory repository, call it through a real HTTP connection on a random port, and throw it away, without any global state leaking between tests.

Pagination and the monthly report

Lucy's list of runs by day and the drivers' own history use the same cursor pagination as the partner service. Each page carries an opaque cursor that encodes the sort position of its last item, here the pickup time and the run id, and the next request passes that cursor back. Unlike page numbers, cursors do not skip or repeat items when new runs are added while someone is reading, which happens constantly on a busy afternoon.

The monthly report is different: it is one aggregate query, grouped by donor and category, that adds grams and counts runs by status for a month in the kitchen's time zone. Mira and Theo spend an hour on its SQL, because the first version counted withdrawn offers as missed pickups. The fix was to count missed pickups as offers that were never claimed plus runs marked missed, and to report withdrawn offers separately, which is what Lucy actually wanted to know.

Worked problem

Choosing status codes

Odalys asks what each of these claim requests should return: (a) the body is fine but the offer id belongs to an offer that has expired; (b) the caller is signed in as a receiver, not a driver; (c) the offer is open but the driver already has three runs that day; (d) the offer id is 9,999,999, which does not exist; (e) the request has no token at all.

Show solution
  1. (a) Expired offer: the request conflicts with the state of the resource, so 409 with a detail saying the pickup window has passed.
  2. (b) Wrong role: the caller is authenticated but not allowed this action, so 403.
  3. (c) Daily limit: a rule about the caller's other runs, so 409 with the reason.
  4. (d) Unknown id: 404.
  5. (e) No token: 401, with a WWW-Authenticate header.

Answer: The answers are 409, 403, 409, 404 and 401. The 403 in (b) is safe because the role, not an object, is the problem; for an object owned by someone else, the API would return 404.

Common mistakes

  • MistakeWriting handlers first and documenting the API afterwards.

    InsteadWrite the API contract first so screens and tests can be built in parallel.

  • MistakeAccepting any fields in a request body.

    InsteadUse a strict schema that refuses unknown fields and checks types, ranges and formats.

  • MistakePutting business rules in route handlers.

    InsteadKeep handlers thin and put rules in services that can be tested without HTTP.

  • MistakeReturning 403 for another person's object.

    InsteadReturn 404 so the response does not confirm the object exists.

  • MistakeLetting retries create duplicates.

    InsteadRequire an Idempotency-Key on creating requests and replay the stored response.

Summary and key terms

  • The rescue API follows the studio's conventions: a versioned prefix, JSON, RFC 9457 problem details, cursor pagination and idempotency keys.
  • The contract is written first, from the stories.
  • Status-changing actions are sub-resources with their own rules and roles.
  • Every body is validated by a strict schema at the trust boundary, with field errors returned as 422.
  • Handlers stay thin: validate, identify, call one service function, map the result.
  • Service errors carry kinds that map to status codes, and unexpected errors become a 500 without internal details.
  • Objects are always loaded with the caller's identity, and inaccessible objects are reported as not found.
  • Idempotency keys make retries from flaky connections safe.
  • The Express app is built by a factory that receives its dependencies, so tests can use in-memory versions.
API contract
A written description of an API's endpoints, inputs, outputs and errors, agreed before coding.
Problem details
The RFC 9457 JSON format for describing HTTP API errors.
Schema validation
Checking that input has the required shape, types and limits before using it.
Handler
The function that turns an HTTP request into a call to the service and a response.
Object-level authorization
Checking that the caller may act on the specific object, not just on that kind of object.
Idempotency key
A client-chosen key that lets a server recognize and safely replay a repeated request.
Cursor pagination
Paging by an opaque marker of the last item seen, which does not skip or repeat items when data changes.
Middleware
Code that runs for every request before or after the handler, such as logging or authentication.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Why does the API refuse unknown fields?

    Show answer

    An unexpected field is either a client bug or someone probing, and accepting it hides both.

  2. Why return 404 rather than 403 for another driver's run?

    Show answer

    403 would confirm the run exists; 404 reveals nothing.

  3. What does a repeated request with the same idempotency key get?

    Show answer

    The same response as the first time, with nothing created twice.

  4. Why is the Express app built by a factory function?

    Show answer

    So tests can create an app with in-memory dependencies and no shared global state.

Try it yourself

Problem details

Complete problem(kind, detail). It returns an object with status, title and detail.

Kinds: invalid is 422 "Request body is not valid", not_found is 404 "Not found", conflict is 409 "The request conflicts with a rule". Any other kind is 500 "Internal error" with no detail (use undefined).

function problem(kind, detail) {
  return { status: 200, title: '', detail };
}

console.log(problem('conflict', 'Overlaps another run.'));
console.log(problem('not_found', 'No such run.'));
console.log(problem('boom', 'socket hang up'));

Try it yourself

Validating a receipt

Complete checkReceipt(body, chilled). It returns a list of error strings, empty if the body is valid.

grams must be a whole number from 1 to 500000. If chilled is true, tenthsC must be a whole number from -300 to 200; if it is above 40, add too warm. If chilled is false, tenthsC must be absent.

function checkReceipt(body, chilled) {
  return [];
}

console.log(checkReceipt({ grams: 18400, tenthsC: 35 }, true));
console.log(checkReceipt({ grams: 18400, tenthsC: 52 }, true));
console.log(checkReceipt({ grams: 0 }, false));
console.log(checkReceipt({ grams: 9000, tenthsC: 30 }, false));
console.log(checkReceipt({ grams: 9000 }, true));

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz