Bitpath

API Design

Design HTTP APIs that other people can build on: resources and status codes, JSON contracts, authentication, rate limits, and GraphQL where it fits. You finish able to change a live API without breaking the clients that depend on it.

  • Intermediate
  • 4 units, 12 lessons, 152 exercises
  • HTTP as text, JSON
  • Builds on Networking helps

Unit 01 · 3 lessons

Resources and verbs

Design URLs, methods and status codes that every HTTP tool already understands

  1. > start01Resources
  2. 02Status and errors
  3. BOSSDesign a small API
Unit prize
  1. 01
    Resources

    Nouns in the URL, verbs in the method, and what each method promises

  2. 02
    Status and errors

    The right code for each outcome, and an error body a client can act on

  3. BOSS
    Design a small API

    Orders for a shop: URLs, bodies, filters, and paging that survives change

Read the unit guide

An API built on HTTP has a vocabulary before you write a line of it. A resource is a thing you expose: a book, an order, a user. Its URL is a noun that names it. A collection (/orders) holds items (/orders/41), and something that belongs to an item nests one level under it (/orders/41/items).

The method says what to do. GET reads. POST on a collection adds a new item and lets the server choose the id. PUT replaces the whole resource with the body. PATCH changes only the fields it mentions. DELETE removes. GET and HEAD are safe: they change nothing, so anything may repeat them. PUT and DELETE are idempotent: twice equals once, so they can be retried. POST and PATCH promise neither.

The status code is the part of a reply that machines read. 200 worked, 201 created something (with Location saying where), 204 worked and has no body. 4xx means the request must change before it can succeed: 400 malformed, 401 who are you, 403 not allowed, 404 no such thing, 409 clashes with the current state, 422 well-formed but invalid. 5xx means the server failed: 500 is a bug, 503 is "not now". Never send a failure as 200.

An error body should let code and people both act: a stable identifier for the kind of problem, a readable message, and the data needed to fix the request. The problem details format (application/problem+json) is a standard shape for that.

Filtering, sorting and paging are views of one collection, so they live in the query string. Offset paging ("skip 40, take 20") can jump to any page, but duplicates or skips items when the list changes underneath. Cursor paging ("20 after this id") is stable under change and can only move forward. Feeds want cursors; slow-moving admin tables can live with offsets.

The classic mistake is to treat HTTP as a tunnel: every call a POST, verbs in the path, 200 for everything, the real answer hidden in the body. It works until the first cache, retry, monitor or new client developer meets it.

Unit 02 · 3 lessons

Contracts

Shape JSON so that clients can rely on it, change it without breaking them, and retry without doing things twice

  1. 01JSON shapes
  2. 02Change without breaking
  3. BOSSRetries without double charges
Unit prize
  1. 01
    JSON shapes

    Ids, times, money, null and lists in shapes that survive every client

  2. 02
    Change without breaking

    Additive against breaking changes, tolerant readers, versions and deprecation

  3. BOSS
    Retries without double charges

    A lost reply, a retry, and the key that makes paying twice impossible

Read the unit guide

The shape of the data is the API. Clients are written against it once and then run for years, so a few habits pay for themselves. Ids are strings: they are names, not quantities, and large numbers are silently rounded by any client that holds numbers as 64-bit floats. Timestamps are ISO 8601 in UTC (2024-03-10T14:30:00Z). Money is an integer count of the smallest unit plus a currency code. Lists are wrapped in an object ({"data": [...], "next": ...}) so there is room to add things later.

Missing and null are different messages. Decide for every member whether it is always present (possibly null) or optional, and what each means in a request: in a PATCH, "not mentioned" usually means leave alone and null means clear. A schema (JSON Schema, usually inside an OpenAPI document) writes all of this down so that servers can validate, clients can generate types, and both can test against it.

A change is breaking if a client that changes nothing can stop working. Adding an optional member, endpoint or parameter is safe, provided clients are tolerant readers that ignore what they do not recognise. Removing, renaming or retyping a member, changing its meaning, or requiring a new input is breaking. New enum values sit in between: tell clients to expect unknown values.

Most APIs can live on one version for years by only adding. When something must go, add the replacement beside it, mark the old thing deprecated (docs, plus Deprecation and Sunset headers), give clients time, then remove it after the date. A new version (/v2 in the path, or a header) is a promise to keep the old one alive too, so save it for changes that cannot be made additively.

Networks lose replies, so clients retry, and a retried POST repeats its effect. An idempotency key fixes that: the client invents a unique key per intended action and sends it with every attempt; the server stores the key with the reply and replays it for repeats. Store the key in the same transaction as the effect, reject a known key with a different body, and return the original reply, not an error. The alternative is to let the client choose the id and PUT to it.

The classic pitfall is the silent change: same member name, new meaning (dollars become cents, local time becomes UTC). Nothing errors and every old client is now wrong.

Unit 03 · 3 lessons

Who is calling

Identify callers, let apps act for users without passwords, and stop any one caller from taking the whole API

  1. 01Authentication
  2. 02OAuth
  3. BOSSProtect the API
Unit prize
  1. 01
    Authentication

    Keys, cookies and tokens: where they travel, what to check, 401 against 403

  2. 02
    OAuth

    An app acts for a user without the password: codes, PKCE, scopes and two tokens

  3. BOSS
    Protect the API

    Token buckets, 429 and Retry-After, quotas, signed webhooks and what CORS is not

Read the unit guide

Every request must answer "who is this?". An API key is a long random secret for a program or a project: long-lived, so it stays on servers. A session cookie identifies a browser and is looked up on every request. A bearer token is a short-lived credential in the Authorization header. Credentials never go in URLs, because URLs are copied into logs, history and referrers.

A JWT is a token the API can check without a lookup: three base64url parts (header, payload, signature). Anyone can read it; only the key holder can produce one that verifies. Check the signature, then the claims: exp (still valid?), aud (meant for this API?), iss (from our issuer?). Because nothing is looked up, a stolen token works until it expires, which is why access tokens live for minutes. 401 means "I do not accept your credential": get a new one. 403 means "I know you, and no".

OAuth lets an app act for a user without their password. The user logs in at the authorization server and approves a list of scopes; the browser returns to the app with a one-time code; the app trades the code for tokens over a direct connection. PKCE ties the two halves together: the app sends the hash of a random verifier at the start and the verifier itself at the end, so a stolen code is useless. state ties the reply to the browser that started the flow.

The app gets a short-lived access token for the API and a longer-lived refresh token that it shows only to the authorization server. Scopes cap what the token may do, whatever the user could do. A service with no user uses the client credentials grant and logs in as itself.

Knowing who is calling is not enough: one caller can still drown the rest. A token bucket per key allows bursts up to its capacity and a steady average at its refill rate. Over the limit, answer 429 with Retry-After. Quotas apply the same idea over a day or a month. Outgoing webhooks are signed with an HMAC so the receiver can tell yours from forgeries.

The classic pitfall is to mistake CORS for security. It is a rule browsers follow to protect their users; scripts ignore it. An API is protected by credentials, permissions and limits, checked on every request.

Unit 04 · 3 lessons

Beyond REST

Know what GraphQL and RPC buy and cost, and change a live API without breaking the clients that depend on it

  1. 01GraphQL
  2. 02What GraphQL costs
  3. BOSSEvolve a live API
Unit prize
  1. 01
    GraphQL

    A query with the shape of its answer, a schema of types, and one endpoint

  2. 02
    What GraphQL costs

    N+1 resolvers, caching without URLs, errors inside a 200, and when REST or RPC fits better

  3. BOSS
    Evolve a live API

    Add, rename and split on an API with 300 clients, with no flag day, then review a flawed design

Read the unit guide

In REST the server decides the shape of each reply. In GraphQL the client does: it sends a query that looks like the answer it wants, and gets back exactly those fields under "data". A schema of types says what can be asked; ! marks what is never null. A query that names an unknown field is rejected before anything runs. Reads are queries, writes are mutations, and all of it goes to one endpoint.

That freedom has a bill. Each field is filled in by its own resolver, so a list of 50 orders with a customer each becomes 51 database queries unless the server batches the lookups. One request can ask for a million objects, so servers cap depth or cost before running a query. Every query goes to the same URL, usually as a POST, so HTTP caches do not help. And a failed field arrives inside a 200 reply, in "errors": clients and dashboards must read it.

So choose by fit. REST suits public APIs built from resources that cache well. GraphQL suits many screens that each need a different slice of connected data. RPC, a typed function call across the network, suits calls between services you own.

Whatever the style, an API is a promise to code you cannot see. Adding something optional is safe, because good clients ignore what they do not know. Removing, renaming, or changing what a name means breaks someone.

A breaking change is done in three steps: expand (serve old and new side by side), migrate (announce a date, help clients move, measure who still uses the old form), contract (remove it). When many breaking changes pile up, ship them together as one new version that runs beside the old one until its Sunset date.

The pitfall is the flag day: one moment when the server and every client must change together. You do not control when other people deploy, so a plan that needs a flag day is a plan to break them.

Learn API Design on your phone.

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy