JS-240 · Lesson 1 of 12 · 27 min

Designing good APIs

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

On Tuesday, June 6, 2028, Gareth and Mira start their tenth block of sessions in the studio, a week and a half after the partner order API's pilot review. The review on Friday, May 26 had good news and three problems. In four weeks the three partner agencies placed 61 orders through the API, no order was copied twice, and Rosa stopped retyping phone messages. But Theo, looking at the Westview Youth Drop-In's own staff page while the review was going on, found the agency's API key written into its JavaScript, where anyone who opened the page's source could copy it. He revoked the key before the meeting ended. Rosa still prints the day sheet each morning and walks to the office to check whether anything changed overnight. And the agencies phone the kitchen to ask whether a change went through, because nothing tells them.

This lesson opens a course about the parts of a back end that come after the first working version: designing an API that other people can rely on, versioning and documenting it, knowing who is calling it and what they may do, protecting it from overuse, and pushing changes to people as they happen. It starts with design, because every later decision is easier when the API underneath is consistent. By the end, Mira has checked the partner API against a written set of design rules and fixed the two places where it breaks them.

Three problems and a plan

Gareth writes the review's findings on the whiteboard and turns each one into part of the course. The leaked key shows that an agency key, a secret meant for a server, was being used to identify people sitting at a browser. People need to sign in, with sessions or tokens that belong to them, and the service must know which agency and which person each request comes from. Rosa's printed day sheet should become a live order board on a tablet in the kitchen. And the agencies' phone calls should become notifications: a message when the kitchen marks an order delivered or changes a delivery day, and an update on the partner page without a reload.

The plan for the course
LessonsTopicWhat it adds to the partner service
1 and 2API design, versioning and documentationConsistent rules, a changelog and a deprecation plan
3 to 6Sessions, tokens, OAuth and authorizationStaff sign-in, sign-in with work accounts and role checks
7Rate limiting and abuse protectionLimits per person, per agency and for sign-in attempts
8 and 9WebSockets, server-sent events and notificationsLive updates and delivery messages
10 and 11GraphQL and file uploadsA reporting prototype and dietary form attachments
12CapstoneThe real-time order board in the kitchen

Theo's PHP application remains the Food Hub's main back end. The partner service is still the small Node service Mira built in March and April, running beside it on Theo's server and sharing nothing with the volunteer data except the machine. Everything in this course is planned for June and July 2028, with the new features going live after a review on Thursday, July 20.

What makes an API good

An API is a promise. Once Northside Family Shelter's case management system sends orders to POST /api/partners/v1/orders, the shape of that request, the meaning of every field and every status code become things the studio has agreed to. A good API keeps its promises and makes them easy to understand. Gareth lists five qualities that the rest of the lesson turns into rules.

  • Predictable. Once a client has used one endpoint, it can guess how the others work: the same names, the same error shape, the same paging.
  • Hard to misuse. Dangerous operations are explicit, defaults are safe, and a mistake produces a clear error rather than a silent wrong result.
  • Designed for its clients. The JSON describes what an agency or the kitchen needs, not how the database stores it.
  • Stable. Changes add things rather than change or remove them, and anything that must break is announced well in advance.
  • Secure by default. Every request is authenticated unless it is deliberately public, and every object is checked against the caller before it is returned.

The order of the list is not the order of importance. An API that is predictable but insecure is worse than useless, because predictable mistakes are the ones attackers find first. The security quality is last only because the following lessons spend most of their time on it.

Resources and URLs

In a REST API, URLs name resources, the things the API is about, and HTTP methods say what to do with them. The partner service's resources are the menu, orders, delivery days and, from this course on, staff members and notifications. Collections are plural nouns, a single member is the collection followed by its id, and a resource that only makes sense inside another can be nested one level, as in /orders/17/attachments. Words for actions, such as create or getOrders, stay out of the path, because the method already says what is happening.

URL rules for the partner API
AvoidPreferWhy
GET /getOrdersGET /ordersThe method already says get
POST /orders/17/deleteDELETE /orders/17Use the method that means remove
GET /Orders/17/GET /orders/17Lowercase, no trailing slash, one spelling
GET /orders?agency=northsideThe agency comes from the callerClients must not choose whose data they see
/delivery_days, /deliveryDays/delivery-daysOne style for paths: lowercase words joined by hyphens

The fourth row is about more than style. An earlier draft of the order list took the agency as a query parameter, which meant one agency could ask for another's orders by changing a word in the URL. In the partner service, the agency always comes from the credentials on the request, never from something the client typed. Lesson 6 calls this mistake by its common name, broken object level authorization, and shows how to test for it.

Mira turns the rules into a small checker, so that every new endpoint in the design document can be tested before anyone writes code for it.

JavaScript Example · A URL rule checker
// Check proposed endpoints against the partner API's URL rules.
const rules = [
  ['lowercase only', (p) => p === p.toLowerCase()],
  ['no trailing slash', (p) => p === '/' || !p.endsWith('/')],
  ['hyphens, not underscores', (p) => !p.includes('_')],
  ['no verbs in the path', (p) => !/\/(get|create|update|delete|add|remove)[a-z-]*(\/|$)/i.test(p)],
  ['plural collection names', (p) => p.split('/').filter((s) => s && !s.startsWith(':') && s !== 'v1').every((s) => s.endsWith('s') || ['menu', 'me', 'staff'].includes(s.toLowerCase()))],
];

function check(method, path) {
  const broken = rules.filter(([, ok]) => !ok(path)).map(([name]) => name);
  return `${method.padEnd(6)} ${path.padEnd(32)} ${broken.length ? 'breaks: ' + broken.join(', ') : 'ok'}`;
}

[
  ['GET', '/v1/orders/:id'],
  ['POST', '/v1/orders/:id/delete'],
  ['GET', '/v1/delivery_days/'],
  ['GET', '/v1/Staff'],
  ['GET', '/v1/me/notifications'],
].forEach(([m, p]) => console.log(check(m, p)));
Output
GET    /v1/orders/:id                   ok
POST   /v1/orders/:id/delete            breaks: no verbs in the path, plural collection names
GET    /v1/delivery_days/               breaks: no trailing slash, hyphens, not underscores
GET    /v1/Staff                        breaks: lowercase only
GET    /v1/me/notifications             ok

What this code does

Each rule is a name and a test function, so adding a rule means adding one line to the list. The checker runs every rule against a path and reports the names of the ones that fail, which turns a style guide into something a review can apply mechanically. The last path passes because me is allowed as a special name for the signed-in caller, a common convention that the next sections use.

The path /me deserves a word. Many APIs give the signed-in caller a fixed name, so that GET /me returns the caller's own profile and GET /me/notifications returns their notifications. It reads well, and it removes a whole class of mistakes: there is no id in the URL for the client to change.

Methods, status codes and errors

The partner service already follows the method rules from JS-230: GET is safe and never changes anything, PUT and DELETE are idempotent, POST creates or runs an action and needs an Idempotency-Key, and PATCH applies a JSON Merge Patch. Its errors are RFC 9457 problem details, each with a type, a title, a status and, for validation errors, a list of what was wrong. That consistency is worth protecting. Every new endpoint in this course returns the same error shape, including the sign-in endpoints, the upload endpoint and the real-time streams when they refuse a connection.

Status codes the partner service uses
StatusMeaning in the partner service
200 / 201 / 204Done; 201 when something was created, 204 when there is no body
400The request cannot be read at all (broken JSON, wrong content type)
401No valid credentials: sign in or send a key
403Known caller, but not allowed to do this
404Not found, including objects that belong to another agency
409 / 412A rule or a version check failed (cut-off, capacity, If-Match)
422The request was read, but values are invalid
429Too many requests; try again after the time given
500 / 503Our fault, or temporarily unavailable

One row is a deliberate choice: an order that belongs to another agency is answered with 404, not 403. A 403 would confirm that order 17 exists and belongs to someone else, which is information an agency has no business learning. Pretending the object does not exist gives away nothing.

Mira writes the error-response helper as a small function that all new code will call, so that no handler builds a problem object by hand.

JavaScript Example · One helper for every error
const TYPES = {
  401: ['unauthenticated', 'Sign in or send a valid key'],
  403: ['forbidden', 'You are not allowed to do this'],
  404: ['not-found', 'Not found'],
  422: ['invalid', 'Some values are invalid'],
  429: ['rate-limited', 'Too many requests'],
};

function problem(status, extra = {}) {
  const [slug, title] = TYPES[status] ?? ['error', 'Something went wrong'];
  return {
    status,
    headers: { 'content-type': 'application/problem+json' },
    body: { type: `https://partners.riverside-food-hub.example/problems/${slug}`, title, status, ...extra },
  };
}

const res = problem(422, { errors: [{ field: 'lines[0].trays', message: 'must be 1 to 10' }] });
console.log(res.status, res.headers['content-type']);
console.log(JSON.stringify(res.body, null, 2));
console.log(problem(429, { retryAfter: 20 }).body.title);
Output
422 application/problem+json
{
  "type": "https://partners.riverside-food-hub.example/problems/invalid",
  "title": "Some values are invalid",
  "status": 422,
  "errors": [
    {
      "field": "lines[0].trays",
      "message": "must be 1 to 10"
    }
  ]
}
Too many requests

What this code does

The helper looks up a short name and a title for each status, then builds the response with the problem details content type and the standard fields. Extra fields, such as the list of validation errors, are spread into the body, so each kind of error can carry its own details while keeping the common shape. A status that is not in the table falls back to a generic title instead of failing.

Designing for the client

A representation is the JSON a client sends and receives. It should describe what the client needs, in the client's terms. Rosa's board, which lesson 12 builds, needs for each delivery day the agency names, the trays per item and the status of each order, and it needs them in the order the van is loaded. The database has these spread over four tables with numeric partner ids. The API's job is to translate.

Designing for the client also means not sending too much. The OWASP API Security Top 10, a list of the most common API weaknesses published by the Open Worldwide Application Security Project in 2019 and revised in 2023, calls one of them broken object property level authorization: returning, or accepting, properties that the caller should not see or set. A response built by sending the whole database row, with the stored key hash and internal notes, is the classic example. So is accepting a status field from an agency that only the kitchen should be able to set. The cure is to build every response from an explicit list of fields, and to accept only an explicit list.

JavaScript Example · Allow-lists for reading and writing
// Build responses and accept input from explicit lists, never from the whole row.
const row = { id: 17, partner_id: 2, delivery_date: '2028-06-14', status: 'received',
  note: 'Two vegetarian', internal_note: 'Called twice about stew', key_hash: '9f2c...' };

const VIEW = {
  partner: ['id', 'deliveryDate', 'status', 'note'],
  kitchen: ['id', 'deliveryDate', 'status', 'note', 'internalNote'],
};
const toApi = { id: 'id', delivery_date: 'deliveryDate', status: 'status', note: 'note', internal_note: 'internalNote' };

function represent(row, role) {
  const out = {};
  for (const [col, name] of Object.entries(toApi)) if (VIEW[role].includes(name)) out[name] = row[col];
  return out;
}

const WRITABLE = { partner: ['note'], kitchen: ['note', 'status', 'internalNote'] };
function acceptPatch(body, role) {
  const extra = Object.keys(body).filter((k) => !WRITABLE[role].includes(k));
  return extra.length ? `422: not allowed to set ${extra.join(', ')}` : 'accepted';
}

console.log(represent(row, 'partner'));
console.log(represent(row, 'kitchen'));
console.log(acceptPatch({ note: 'Three vegetarian' }, 'partner'));
console.log(acceptPatch({ status: 'delivered' }, 'partner'));
Output
{ id: 17, deliveryDate: "2028-06-14", status: "received", note: "Two vegetarian" }
{ id: 17, deliveryDate: "2028-06-14", status: "received", note: "Two vegetarian", internalNote: "Called twice about stew" }
accepted
422: not allowed to set status

What this code does

The represent function copies only the fields that the caller's role may see, translating database column names into API names on the way, so the key hash and the partner id never leave the server. acceptPatch does the same in the other direction and refuses any field the role may not set, which stops an agency from marking its own order delivered. Both lists are written out by hand, so adding a column to the table can never expose it by accident.

A diagram of an API request passing through four checks from left to right: authenticate (who is calling), authorize (may they do this to this object), validate (is the input allowed and correct) and represent (which fields go back). A red cross under the first three shows where a request can be refused with 401, 403 or 404, and 422.
Every request passes the same four checks; this course adds the first two properly.

The OWASP API Security Top 10

Gareth hands Mira a printed copy of the 2023 list and asks her to mark which items the partner service already handles. It becomes the checklist for the course.

The OWASP API Security Top 10 (2023) and the lessons that address it
NumberWeakness (2023)Where this course handles it
API1Broken object level authorizationLesson 6
API2Broken authenticationLessons 3 to 5
API3Broken object property level authorizationThis lesson; lesson 6
API4Unrestricted resource consumptionLessons 7 and 11
API5Broken function level authorizationLesson 6
API6Unrestricted access to sensitive business flowsLesson 7
API7Server-side request forgeryLesson 11
API8Security misconfigurationLessons 3, 8 and 12
API9Improper inventory managementLesson 2
API10Unsafe consumption of APIsLessons 5 and 10

Improper inventory management, the ninth item, is the surprise on the list for most developers. It means not knowing which versions of an API are running and who uses them, so that an old, forgotten version without the latest checks stays reachable. The partner service has one version today, and lesson 2 makes sure it stays that way on purpose.

Worked problem

Fixing the endpoint list

Mira's first draft for the new features proposed these endpoints: GET /v1/getNotifications, POST /v1/orders/:id/markDelivered, GET /v1/kitchen/Board/ and GET /v1/staff?agency=westview. Rewrite each so it follows the URL rules, and say what is wrong with the last one beyond style.

Show solution
  1. GET /v1/getNotifications names an action; the caller's notifications are a resource: GET /v1/me/notifications.
  2. POST /v1/orders/:id/markDelivered puts a verb in the path; changing the status is a partial update: PATCH /v1/orders/:id with a body of status delivered, allowed only for the kitchen role.
  3. GET /v1/kitchen/Board/ has a capital letter and a trailing slash: GET /v1/kitchen/board.
  4. GET /v1/staff?agency=westview lets the client choose the agency; the agency must come from the caller's credentials: GET /v1/staff, returning the caller's own agency's staff.

Answer: Four corrected endpoints. The last change is a security fix, not a style fix: with the agency in the query string, any staff member could list another agency's staff by editing one word.

Common mistakes

  • MistakeA REST URL should describe the action, such as /orders/17/delete.

    InsteadURLs name resources; the HTTP method says what to do with them.

  • MistakeA 403 is the right answer to a request for another agency's order.

    Instead404 gives away nothing; 403 confirms that the order exists.

  • MistakeSending the whole database row is simpler and harmless.

    InsteadIt leaks fields such as hashes and internal notes. Build responses from an explicit list of fields.

  • MistakeClients can pass the agency as a parameter as long as the form fills it in.

    InsteadAnyone can edit a request. The agency comes from the credentials, never from the client.

Summary and key terms

  • A good API is predictable, hard to misuse, designed for its clients, stable and secure by default.
  • URLs name resources with plural lowercase nouns, ids and at most one level of nesting; methods carry the action, and /me names the signed-in caller.
  • The partner service keeps one error shape, RFC 9457 problem details, for every endpoint, and answers requests for other agencies' objects with 404.
  • Responses are built from an explicit list of fields for the caller's role, and input is accepted only for fields the role may set.
  • The OWASP API Security Top 10 (2023) lists the most common API weaknesses and is the checklist for this course.
Resource
A thing an API is about, such as an order, named by a URL.
Representation
The JSON a client sends or receives for a resource.
Problem details
The standard JSON error format of RFC 9457, with type, title and status.
Allow-list
An explicit list of what is permitted; anything not on it is refused.
OWASP API Security Top 10
A published list of the ten most common kinds of API weakness, last revised in 2023.
BOLA
Broken object level authorization: returning or changing an object without checking that it belongs to the caller.
BOPLA
Broken object property level authorization: exposing or accepting properties the caller should not see or set.
Inventory management
Knowing which API versions and endpoints exist, who uses them and when each will be retired.

Practice problems

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

  1. Why is /orders/17/delete a poor URL?

    Show answer

    It puts an action in the path; DELETE /orders/17 says the same thing with the method.

  2. What does GET /me/notifications return, and why is /me safer than /staff/42/notifications?

    Show answer

    The signed-in caller's notifications; there is no id for the client to change.

  3. Why does the partner service answer 404 for another agency's order?

    Show answer

    So that it does not confirm that the order exists.

  4. Give one example of broken object property level authorization.

    Show answer

    Returning the stored key hash in a response, or letting an agency set the status field.

  5. Which OWASP item is about forgotten old API versions?

    Show answer

    API9, improper inventory management.

Try it yourself

Check the method

Complete checkMethod(method, path) so that it returns a warning string for endpoints that misuse HTTP methods, and ok otherwise.

Return GET must not change anything when the method is GET and the path contains /withdraw, /delete or /mark. Return use DELETE instead when the method is POST and the path ends with /delete. Otherwise return ok.

function checkMethod(method, path) {
  return 'ok';
}

console.log(checkMethod('GET', '/v1/orders/17'));
console.log(checkMethod('GET', '/v1/orders/17/withdraw'));
console.log(checkMethod('POST', '/v1/orders/17/delete'));
console.log(checkMethod('DELETE', '/v1/orders/17'));

Try it yourself

Represent an order for its caller

Complete represent(row, role) so that it returns an object with API names. For the role partner, include only id, deliveryDate and status. For the role kitchen, also include agency.

The row uses database names: id, delivery_date, status, agency_name and key_hash. The key_hash must never appear in any representation.

function represent(row, role) {
  return { ...row };
}

const row = { id: 21, delivery_date: '2028-06-16', status: 'received', agency_name: 'Northside Family Shelter', key_hash: 'ab12' };
console.log(JSON.stringify(represent(row, 'partner')));
console.log(JSON.stringify(represent(row, 'kitchen')));

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz