Core Concepts

API Design

Design a link dashboard around the promises its clients rely on, from creating one link to paging through history and handling retries.

Free~17 min

An API contract defines what clients can ask for and what they can depend on. It tells a client when a result is ready to use, which records it can access, and what happens when it retries a request or continues a list.

Define the resource and who can use it

The URL Shortener walkthrough creates links and resolves them for visitors. Here we extend it with an account-owned link dashboard. A saved link has a dashboard record ID such as l104 and a public short code such as guide. The account that creates it owns the record. Visitors can use its short code to reach the destination.

OperationCallerResult
POST /v1/linksSigned-in accountCreate a link owned by this account
GET /v1/links?pageSize=2Signed-in accountList this account's links, newest first
GET /v1/links/l104Account that owns l104Read the saved link
GET /guideVisitor with the short URLRedirect to the destination while the link is active

Authentication establishes the account from the session or credential. Authorization checks whether that account can perform an operation on the requested resource. To fetch l104, the server looks for that ID within the authenticated account's links. It applies the same account restriction when listing or continuing a page. The server assigns the owner from the authenticated identity. A public short code or a private link ID gives a caller something to look up, while access still depends on the operation and account. OWASP on object-level authorization

Give success and failure a shape

Here is a create request from account a7 and the successful response.

POST /v1/links
Idempotency-Key: create-7f
Content-Type: application/json
 
{"destinationUrl":"https://example.com/guide","customAlias":"guide"}
201 Created
Location: /v1/links/l104
Content-Type: application/json
 
{"id":"l104","shortCode":"guide","shortUrl":"https://sho.rt/guide"}

Return 201 Created after the new resource exists. If the API only accepts a job that will create something later, 202 Accepted is a different promise. Give the caller a way to check the outcome. HTTP success statuses

Validation checks whether the request fits the contract. This API accepts absolute HTTP or HTTPS destinations and a short alias matching its documented rules. A malformed destination gets 400 Bad Request with an error the client can show by the field. An alias already claimed by someone else gets 409 Conflict. The service checks that claim in the same database that owns the alias, so two distinct create intents cannot both claim guide. Retries with the original key can still receive its saved success.

Keep errors machine-readable. For an alias conflict, the API can send application/problem+json with the problem type https://api.example.test/errors/alias-taken. The dashboard matches the type and asks for another alias. The visible explanation can change without breaking that choice. For a private link lookup, this example returns the same 404 Not Found for a link outside the account as for a missing link. HTTP problem details

Make the retry mean the same action

Suppose the service saves l104 and its response never reaches the browser. An idempotency key identifies the customer's one attempt to create a link, including any retries of that attempt. The dashboard generates create-7f before the first request and uses it again with the same input.

Scope the key to the account and operation. Store a representation of the validated input and the result alongside the key in the same transaction as the link. A uniqueness rule on that scoped key lets the service arbitrate simultaneous attempts before they create two effects. When a matching retry arrives, return the recorded result. Reusing the key with a different destination or alias gives a conflict for the key itself. If someone chooses a different alias after a conflict, that is a new intent and gets a new key.

Document how long the service retains replay records. After that window, a caller with an unknown outcome needs to look up the previous result or make an explicit new choice. The method POST alone carries no such retry guarantee. See HTTP idempotent methods and Idempotency.

Page by position in a stable order

The dashboard shows two links at a time. It sorts by creation time from newest to oldest, then by ID from highest to lowest for links created at the same time. The ID provides a tie-breaker, so every link has a distinct position.

The first page contains l104 and l103. Then someone adds l105 at the front. If the next query skips the first two rows, it sees l103 again. A cursor tells the server to continue after the last position the caller already saw, so the next page starts at l102.

Return an opaque nextCursor while there is another page. The client copies that value into GET /v1/links?pageSize=2&cursor=.... The service can store the sort position and query scope behind a random token, or encode those fields with an integrity check. It validates the token and authorizes the account on every page, then selects items strictly after the saved position. Return a documented client error for an invalid, expired, or mismatched cursor. Set a maximum page size.

Each page reads the collection again. The cursor can store the last sort values directly, so deleting that row need not prevent continuation. A deleted item can disappear from a later page, and an item added ahead of the cursor can appear after a fresh start. An exact export can require a stable snapshot, a fixed view across all pages. Google's pagination guidance

Change the contract while clients are running

Suppose users want a label next to each link. We can accept an optional label and preserve the previous behavior when it is missing. A response can include the new field if supported clients tolerate extra fields. Test an old client against the new response as well as a new client against the older shape.

Changing the meaning of id, requiring a previously optional field, or turning an alias conflict into an automatic rename changes what existing callers can rely on. Keep the old behavior while clients migrate to an explicitly changed contract, such as a new version. A version only helps if callers can tell which behavior they are getting. Google's backward-compatibility guidance

In an interview, trace one successful request and one failure with real fields and results. Say who owns the resource, what the client retries, and which change would require a new contract.

See also

  • Idempotency - keeping repeated write attempts from applying the effect twice.
  • Consistency Models - what a client should see when it lists immediately after writing.
  • SQL vs NoSQL - matching the store's atomic boundary to the API's promises.
  • REST vs RPC vs gRPC - how different interaction styles and runtimes carry the contract.

Used in

  • URL Shortener - creating a link and resolving a public code are separate operations. Create ties the caller's retry key to the saved result.
  • ChatGPT - the turn submit returns an accepted turn and a stream URL. The API checks conversation ownership and pages back through history.
  • Group Chat with Threads - the API exposes separate histories for the channel and its threads and tracks where each reader left off.

Done reading? Mark it so it sticks in your dashboard.

Discussion