Skip to content
Draft — this lesson has not been reviewed yet. Its facts are sourced, but read it with a critical eye.

API design

The salon platform from lessons 1.1 and 1.2 has one API. The booking page calls it to list a salon’s services and book a slot. It works.

Then you build a phone app for owners, so a stylist can check Saturday’s appointments between clients. It calls the same API, GET /appointments?date=2026-12-05, and each appointment in the answer has start: "14:30". That works too.

A month later you fix a real bug: “14:30” says nothing about the day or the time zone. You rename start to startsAt and make it a full timestamp, 2026-12-05T14:30:00+01:00. The busiest salons now have hundreds of appointments a day, so you make the list return 20 at a time. The booking page changes in the same deploy. The tests pass.

On Saturday morning an owner opens the phone app. Every appointment has a blank time. Only 20 are listed, and nothing says there are more, so she thinks the afternoon is quiet and takes a walk-in at three.

You can ship a fixed app the same day. You cannot make her install it. Last month’s app is still on hundreds of phones, sending last month’s requests.

What broke? The server and the booking page are deployed together, so they always agree. The phone app is not. Once one client ships on its own schedule, the API is a promise to code you cannot redeploy. That promise is the contract. This lesson is about phrasing it, writing it down and changing it.

Terms used in this lesson:

  • An API (application programming interface) is the set of requests a client may send and the responses it gets back. A client is any program that calls it.
  • The contract is everything a client may rely on: requests, response shapes, errors and behaviour. It exists whether or not anyone wrote it down.
  • An endpoint is one method and path, such as GET /appointments. A resource is a thing the API names, such as one appointment or the list of them.
  • A breaking change makes a client that used to work stop working. A backward-compatible change is one that clients already in use survive.
  • A request is idempotent if sending it twice has the same intended effect as sending it once.

An API is a promise to code you cannot redeploy. REST, RPC and GraphQL are three ways to phrase it. Pagination, errors and versioning are the parts clients lean on hardest. Every decision below is one question asked again: what does this let clients rely on, and how will I change it later?

How the rename should have shipped. This is expand and contract: add the new field beside the old one, move the clients over, and remove the old one last.

API serverPhone app, this weekPhone app, last monthAPI serverPhone app, this weekPhone app, last monthStep 1, expand. Add startsAt and keep startIgnores the field it does not know and reads startReads startsAtStep 2, measure. Count requests still coming from 1.4Step 3, contract. Remove start once that count is near zeroGET /appointments, app version 1.4start and startsAtGET /appointments, app version 1.5start and startsAtGET /appointments, app version 1.4An error that says update the app, never a blank screen

It needs two things: an old app that ignores fields it does not know, and a server that knows which app version is calling. Neither can be added later to an app already installed.

One operation, booking the 14:30 slot, in each style:

REST POST /appointments
{"serviceId": "svc_12", "startsAt": "2026-12-05T14:30:00+01:00"}
→ 201 Created, Location: /appointments/apt_88
RPC BookingService.BookAppointment(serviceId, startsAt) → Appointment
(in gRPC, sent as POST /BookingService/BookAppointment)
GraphQL POST /graphql
mutation { bookAppointment(serviceId: "svc_12", startsAt: "...") { id startsAt } }

REST names things and lets HTTP’s methods say what happens to them. Roy Fielding’s 2000 dissertation defined it: “The key abstraction of information in REST is a resource. Any information that can be named can be a resource”. Each request carries “all of the information necessary to understand the request”, and responses are labelled as cacheable or not.

Why does that matter? Because the methods carry a meaning every program on the path can read. RFC 9110 defines it:

Method Use Safe Idempotent
GET read a resource or a list yes yes
PUT replace a resource no yes
DELETE remove a resource no yes
POST create, or any other action no no
PATCH change part of a resource no no (RFC 5789)

A safe method is “essentially read-only”. Idempotent requests “can be repeated automatically if a communication failure occurs”; a client “SHOULD NOT automatically retry” the others. That is the rule nginx followed in lesson 1.2: retry a GET, never a POST. So how does a booking POST become safe to retry? The client sends a unique Idempotency-Key header, and the server “saves the status code and body of the first request” with that key (Stripe’s docs) and replays it for a repeat. Lesson 2.6 builds this.

Fielding wrote in 2008 that an API not driven by hypertext “cannot be RESTful”. Most APIs called REST, this one included, are resource URLs, methods, status codes and JSON, without the links. This course uses “REST” in that everyday sense.

RPC (remote procedure call) names actions instead of things. gRPC lets a client “call a method on a server application on a different machine as if it were a local object”. You define the service’s methods in protocol buffers, and tools generate the client code. It adds streaming and deadlines: a call that runs too long ends with DEADLINE_EXCEEDED.

The cost? Every gRPC call is a POST to /Service/Method, and an error arrives with HTTP status 200 and the real code in a grpc-status trailer. A cache or proxy cannot tell a read from a write. Browsers cannot speak it directly, since HTTP/2 framing “is not, and will never be, directly exposed by browsers”, so web clients need gRPC-Web and a translating proxy. RPC suits services you control at both ends.

GraphQL lets the client choose the fields, at one endpoint, “usually /graphql”. The phone app asks for each appointment’s time and customer name and nothing else, and it can fetch a salon, its services and their free slots in one round trip, which lesson 1.1 showed is what a phone pays for.

The costs land on the server. Twenty appointments that each fetch their customer can become 21 database queries, the N+1 problem, usually fixed by batching with “a tool like Facebook’s DataLoader”. Caching is harder, because queries are POSTs to one URL unless you allow GET for reads. A client can write a very expensive query, so graphql.org advises limiting “the maximum depth of fields that a single operation can have”. A partly failed query still returns a 200, with an errors list.

Does the contract exist if nobody writes it? Yes, and it is bigger than you think. Hyrum’s Law: “With a sufficient number of users of an API, it does not matter what you promise in the contract: all observable behaviors of your system will be depended on by somebody.” The phone app depended on the list being complete. Nobody had promised that.

Each style has a schema language, a machine-readable description of the contract: OpenAPI for HTTP APIs (version 3.2.1, dated 10 September 2026), .proto files for gRPC, the GraphQL schema. Each can generate client code from the same source as the server. This course’s suggestion: one source of truth, every copy generated or imported from it, and a build check that fails on drift.

Then make clients tolerant of one thing: fields they do not know. RFC 9413 states the old rule, “Be strict when sending and tolerant when receiving”, and warns that loose readings of it “can negatively affect interoperability over time”. Ignoring unknown fields is the narrow, useful part: it makes adding a field safe.

Offset pagination turns ?page=3&limit=20 into “skip 40 rows, return 20”. A screen can jump to page 7 and show “page 3 of 12”. It has two problems.

The first is cost. PostgreSQL’s manual: “The rows skipped by an OFFSET clause still have to be computed inside the server; therefore a large OFFSET might be inefficient.” Page 500 computes 9,980 rows only to skip them.

The second is drift. The owner reads page 1. A booking arrives with an earlier time, every row shifts down one, and the last row of page 1 becomes the first of page 2: she sees it twice. A cancellation shifts rows up, and one is never shown. Slack’s engineers met this: with frequent writes, offset pages become “unreliable, potentially skipping or returning duplicate results”.

Cursor pagination asks for “the next 20 after this one”. The server returns a cursor, a token that encodes where the last row was, such as its time and id. The client sends it back, and the query becomes “rows after (14:30, apt_88), sorted by time then id”. Earlier inserts do not move that point, and with an index on those columns a deep page costs about what the first one does.

What does a cursor give up? Slack: “There is no concept of the total number of pages or results in the set”, “The client can’t jump to a specific page”, and the sort needs “a unique, sequential column (or columns)”. Google’s API guide adds that page tokens “must be opaque”, because “if users are able to deconstruct these, they will do so”. An opaque token can change meaning later.

Either way, say whether there is more. Stripe returns has_more, with limit defaulting to 10 and allowed from 1 to 100 (checked 2026-11-29). The phone app had no such field, so 20 looked like everything.

The status code’s class comes first. A 4xx means “the client seems to have erred”; sent again unchanged, it fails again. A 5xx means the server “is aware that it has erred”, and may succeed later if the request is safe to repeat. Within 4xx, use RFC 9110’s meanings: 404 not found, 409 “a conflict with the current state of the target resource”, 422 when the syntax is fine but the server is “unable to process the contained instructions”.

But a status alone is not enough. A Sunday 14:30 booking at a salon that opens at noon and a booking in the past are both 422, and the page should say different things. RFC 9457 defines “machine-readable details of errors”, sent as application/problem+json:

{
"type": "https://api.example.com/problems/outside-opening-hours",
"title": "The salon is closed at that time",
"status": 422,
"detail": "On Sundays this salon is open from 12:00 to 18:00.",
"param": "startsAt"
}

Clients switch on type, the “primary identifier”. detail is for people, and consumers “SHOULD NOT parse” it. param is an extension borrowed from Stripe, where it lets you “display a message near the correct form field”. So: one stable code per cause, a human message beside it, and a client that falls back to a generic message for a code it does not know. A new code is then additive.

Which changes break clients? GitHub’s API lists both kinds. Breaking: “Removing or renaming a response field”, “Adding a new required parameter”. Additive: “Adding a response field”, “Adding an optional parameter”, “Adding enum values”. Google’s AIP-180 adds two more. “Renaming a component is semantically equivalent to ‘remove and add’”, so the opening’s rename was a removal. And “Changing the default value is considered breaking”: the list that went from everything to 20 kept its fields and changed its behaviour.

The two disagree on enums. GitHub calls a new value additive; Google warns that “user code does not handle new values gracefully”. An app that switches on status with no default branch breaks on a new no_show. Which view holds depends on how your clients were written.

When a change must break, there are three common ways to ship it.

A version in the path, such as /v1/appointments. Google puts the major version “as the first part of the URI path”. It shows in every log, and a proxy can route /v2/ to new code (lesson 1.2). But a major version moves every endpoint at once, so it is rare and it hurts.

A dated version per client. At Stripe, “The first time a user makes an API request, their account is automatically pinned to the most recent version”, and each breaking change is a “version change module” that turns a new response back into an old one. GitHub’s X-GitHub-Api-Version header defaults to 2022-11-28, and an old version lives “for at least 24 more months” after a new one (checked 2026-11-29). The cost, in Stripe’s words: “every new version is more code to understand and maintain”.

No versions. GraphQL “takes a strong opinion on avoiding versioning”: clients get only the fields they ask for, so a new field breaks nobody, and old ones are marked @deprecated until no one asks. Protocol buffers evolve the same way, field by field: a field’s number “identifies the field in the message wire format”, so it “should never be reused”.

All three end like the diagram: add first, move clients, measure, remove last.

Roost is a booking platform for businesses that sell their time, such as salons. Its server has three clients: the owners’ dashboard, the customers’ booking pages, and an AI booking agent written in a different programming language from the rest.

The problem. If each client keeps a hand-written copy of the response shapes, the copies drift, and nothing fails until a screen or the agent misreads a field.

The design. Each response shape is written once, as plain types in a shared package in the same repository. The server’s response types are declared to implement them, so a server change that breaks the contract fails the server’s type check. The two web clients import the types. The agent’s models are generated from them through a JSON Schema, and a build check fails if the generated files are stale. Generating client types from an OpenAPI description of the server was considered and not chosen.

Errors carry a short machine-readable code beside the human message; codes are added, never renamed, and an unknown one falls back to the generic error path. One list route serves two readers: page numbers for the booking page; a cursor, a search term and always a total for the agent, which cannot click “next” and must tell “not on this page” from “does not exist”.

The trade-off. The contract is plain shared types, checked when the code is built rather than when a response is sent, and a new field reaches clients only once the contract gains it. That is cheap because all three clients live in one repository and ship with one team.

Honest about scale. Roost is early-stage. No outside developers or app-store apps call this API, so every client can change in the same commit as the server. With a phone app on customers’ devices or partners building on the API, it would need the versioning and deprecation steps above.

REST, RPC or GraphQL. None wins everywhere.

Style Choose it for What it costs
REST public and browser clients; reads that HTTP caches and CDNs can serve round trips for nested data; responses shaped by the server, not the screen
RPC (gRPC) calls between services you control; streaming; strict typed schemas browsers need a translating proxy; caches and proxies see only POSTs
GraphQL many screens reading overlapping data, especially on slow links N+1 queries, harder caching, expensive queries to limit, errors inside a 200

In this course’s view, REST for public clients and gRPC between internal services is a sensible default, not a rule.

Offset or cursor. Offset gives page numbers and totals, which an owner’s table wants, and drifts and slows on deep pages. Cursors are stable and fast at any depth, and give up totals and jumping. This course’s suggestion: cursors for feeds and lists that change while being read, offset for small admin tables.

Where the version lives. A path version is simple and visible, but rare and painful. A dated header lets each client move when ready, and the server carries old shapes for years. No versioning needs discipline, and deprecated fields pile up.

Tolerant clients. Ignoring unknown fields makes additions safe. It also hides a misspelled field, the kind of cost RFC 9413 warns about.

“Design the API for a salon booking platform. Customers see a salon’s services and free slots and book one. Owners see the day’s appointments on a phone app. Which style would you use, what are the main endpoints, and what comes back when booking succeeds, and when the customer picks a time the salon is closed?”

Model answer

Style. REST with JSON. The clients are a public web page and a phone app outside our network, and service lists and free slots are reads worth caching. Four endpoints do not need GraphQL and its N+1 and caching problems, and gRPC does not suit browsers without a proxy.

Endpoints.

  • GET /salons/{id}/services and GET /salons/{id}/slots?serviceId=...&date=....
  • POST /appointments with serviceId, startsAt (a full timestamp with offset) and customer details, plus an Idempotency-Key header so a retry after a dropped connection books once.
  • GET /appointments?salonId=...&date=...&limit=50&after=...: the owner’s day, cursor-paginated, with a next cursor or has_more.

Success. 201 Created, a Location header for the new appointment, and the appointment in the body.

Closed salon. 422 with a problem-details body: a stable type such as outside-opening-hours, a human detail with the hours, and param: "startsAt" so the page shows it beside the time picker. The client switches on type, never on the text.

Rubric
  • Chooses a style and justifies it by the clients, naming one cost of the alternatives — 2
  • Endpoints are resources with correct methods; reads are GET, booking is POST — 2
  • Makes the booking POST safe to retry with an idempotency key — 2
  • Paginates the owner’s list and tells the client whether there is more — 2
  • Success is 201 with a location; the error is a 4xx with a stable machine-readable code — 2

Total 10. 8 or more is a pass.

The interviewer follows up: “Your phone app has been out for a year, and many owners never update. Now you must change start from "14:30" to a full timestamp, and cap the list at 50. How do you ship that without breaking anyone?”

Model answer

Name what breaks. Changing start’s name or type is a removal plus an addition. The cap is a semantic break: an old app assumes the list is complete and silently shows 50.

Expand. Add startsAt beside start, after checking old apps ignore unknown fields. Add limit, a cursor and has_more as optional extras. A request without limit comes from an old app: keep returning it the full day, under a hard maximum far above a real salon’s day.

Move, measure, contract. Ship an app that reads startsAt and pages with the cursor. Count requests by app version. When old versions are near zero, or after an announced notice period, remove start and apply the cap to all. Old apps then get an error that says “update the app”.

Or version it. If the change is too large, put it behind /v2/ or a dated version header and run both until the old traffic is gone. The cost is two shapes to maintain.

Rubric
  • Identifies the rename as breaking and the cap as a semantic break — 2
  • Uses expand and contract: the new field ships before the old one goes — 3
  • Protects old clients from silent truncation — 2
  • Measures client versions before removing anything — 2
  • Names versioning as the alternative, with its cost — 1

Total 10. 8 or more is a pass.

Build the owner’s list and watch offset pagination fail, in any language with SQLite.

  1. Create an appointments table with id, starts_at and customer, and insert 45 appointments for one day, five minutes apart.
  2. Write GET /appointments?page=N&limit=20 with LIMIT and OFFSET, sorted by starts_at.
  3. Fetch page 1, then insert an appointment earlier than everything on it. Predict how page 2 starts, then fetch it. Which appointment appears twice?
  4. Write GET /appointments?limit=20&after=CURSOR, with the last row’s starts_at and id base64-encoded as the cursor, and nextCursor empty on the last page. Repeat step 3.
  5. Send limit=500 and limit=abc, and return a problem-details body for each. Is each a 400 or a 422, and why?
  6. Add serviceName to every appointment. Write one client that rejects unknown fields and one that ignores them. Which survives?

Write one sentence per step on what surprised you.

Answer without notes.

  1. Why can a server and a web page change a field together safely, while the same change breaks a phone app?
  2. Name one situation each for REST, gRPC and GraphQL, and one cost of each.
  3. Which HTTP methods are idempotent? A booking POST times out with no response. How can the client retry it safely?
  4. A list uses page and limit, and new items arrive while users read it. What goes wrong, how does a cursor fix it, and what does the cursor give up?
  5. Is adding a response field breaking? Renaming one? Changing a default? How do you remove a field that old clients still read?