Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 50 ยท Software Design

API and Interface Design

Learn how to design APIs that last: contracts, backward compatibility, versioning, error design and idempotency, with a runnable contract validator.

Every module, library and service has an interface: the set of things other code is allowed to rely on. When that interface is exposed to other programmers, over a network or as a library, we call it an API (application programming interface). Inside one file, a bad interface annoys you; in a public API, a bad interface annoys thousands of people and is nearly impossible to fix, because changing it breaks their programs.

That is why interface design deserves more care than almost any other design activity. The ideas here apply to a function signature, a class, a library and a web API alike. The examples use HTTP-style requests because they are easy to picture, but they run as plain JavaScript stand-ins: there is no real server, and the code only shows how a contract can be written down and checked.

An interface is a contract

An interface is a contract between a provider and its callers. A good contract states:

  • Inputs: what the caller must supply, with types, ranges and which fields are optional.
  • Outputs: what the caller gets back in success.
  • Errors: what can go wrong and how that is reported.
  • Guarantees: things the provider promises, such as "the list is sorted by date" or "this call does not change anything".
  • Obligations: things the caller must do first, such as being authenticated.

Programmers sometimes call these preconditions, postconditions and invariants (the "design by contract" vocabulary). What matters is that the contract is written down and narrower than the implementation. Anything callers can observe, they will eventually depend on. A useful saying is Hyrum's law: with enough users, every observable behavior of your system will be depended on by somebody, even behavior you never promised. So expose as little as you can, and make everything you do expose deliberate.

Principles of good interface design

What good interfaces share

Small Few concepts, each with one clear job.
Consistent Same names and patterns everywhere.
Hard to misuse The easy path is the correct one.
Documented Every promise and every error is written down.

Name things for what callers want, not how you built them.

1 / 2

Concretely:

  • Name by intent. cancelOrder(id) beats updateOrderStatus(id, 5). Magic numbers leak implementation.
  • Be consistent. If one endpoint says created_at and another createdAt, every user must memorize exceptions.
  • Make invalid states unrepresentable. Prefer an enumerated status with known values over a free-form string.
  • Keep the surface small. It is easy to add to an interface and nearly impossible to remove from it.
  • Hide the implementation. Do not return your database rows directly; return a shape you can keep stable while the storage changes. This is information hiding applied at the boundary.

Backward compatibility and versioning

Once clients exist, you must be able to change the system without breaking them. A change is backward compatible if every existing, correct client keeps working.

Generally safe changes:

  • Adding a new optional input field.
  • Adding a new field to a response (provided clients ignore unknown fields).
  • Adding a new endpoint or function.

Generally breaking changes:

  • Removing or renaming a field, endpoint or function.
  • Changing a field's type or meaning (price from dollars to cents).
  • Making an optional input required.
  • Tightening validation so previously accepted input is rejected.
  • Adding a new value to an enumeration that clients do not expect.

When a breaking change is unavoidable, you need versioning. Common approaches are a version in the URL (/v1/orders), in a header, or in a library's version number. Semantic versioning (major.minor.patch) encodes the promise: a major bump may break, minor adds features compatibly, patch fixes bugs; see configuration and change management for details. A good versioning habit is the deprecation path: announce, give a date, keep the old version running for a stated period, measure who still uses it, and only then turn it off. A well-designed API follows Postel's robustness principle with care: be strict in what you send and tolerant of unknown extras in what you receive, but do not silently accept garbage that will cause trouble later.

Error design

Errors are part of the interface, and they are used under stress, at the moment a developer is already confused. Good error design:

  • Separates client errors (bad input, not found, not allowed) from server errors (our bug or outage). In HTTP these are the 4xx and 5xx status code families.
  • Returns a stable machine-readable code ("out_of_stock") as well as a human message, so clients can branch on the code without parsing prose.
  • Says what to do next, and points to the field that was wrong ("field": "quantity").
  • Uses one consistent shape for all errors.
  • Never leaks internals such as stack traces or SQL.

A typical error body:

JSON
{
  "error": {
    "code": "invalid_quantity",
    "message": "quantity must be between 1 and 10",
    "field": "quantity"
  }
}

Idempotency

An operation is idempotent if doing it several times has the same effect as doing it once. Setting a value (status = "shipped") is idempotent; "add one to the balance" is not. This matters because networks fail in an ugly way: a client sends a request, the connection drops, and it does not know whether the server processed it. The safe reaction is to retry, but a retry of a non-idempotent operation might charge a customer twice.

The usual remedy for operations that must not repeat, such as payments, is an idempotency key: the client generates a unique token for each intended action and sends it with the request; the server remembers the result under that key and returns the stored result for any repeat. In HTTP, GET, PUT and DELETE are defined to be idempotent while POST is not, which is why payment APIs add a key to their POST calls.

The stand-in below simulates a server with and without idempotency keys. It is a model of the idea, kept in memory; real servers must store keys durably and expire them.

JS Retries with and without an idempotency key

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Both servers received the same three requests; only the keyed one recognized that they were one intention. That is the whole idea, and the reason you should design any "create" or "pay" call to be safely repeatable.

Writing the contract down and checking it

A contract that exists only in someone's head is not a contract. Teams write it down as a schema (OpenAPI, JSON Schema, a type definition), then use it to validate both requests and responses and to detect breaking changes. The stand-in below keeps a contract as a plain object and checks sample requests against it. A real schema tool does much more; this one only shows the principle: the rules live in data, and the validator is generic.

JS Validate requests against a contract

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Request 6 shows an unknown field passing; whether to accept or reject unknown fields is itself a contract decision, and ignoring them makes it easier to evolve. The error codes are stable and machine-readable, as recommended above. Because the contract is data, you could also compare two versions of it and flag a removed field, a newly required field or a tightened range as breaking.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which change to a public API is generally backward compatible?

    Existing clients do not send the new field, so they keep working. The other changes break clients.
  2. 2. Why use an idempotency key for a payment request?

    The server stores the result under the key and replays it for repeats, so retries after a network failure are safe.
  3. 3. What makes an error response most useful to client developers?

    A stable code lets programs branch, the message helps people, and a consistent shape means one handler works for all errors.
  4. 4. What does Hyrum's law warn about?

    With enough users, any observable behavior becomes a de facto part of the contract, so expose deliberately.
  5. 5. Which HTTP method is not defined as idempotent?

    POST usually creates something new each time, so repeating it can have additional effects; GET, PUT and DELETE are defined to be idempotent.

Summary

  • An interface is a contract: inputs, outputs, errors, guarantees and obligations, written down and narrower than the implementation.
  • Good interfaces are small, consistent, hard to misuse and named by intent.
  • Adding optional things is compatible; removing, renaming, retyping or tightening is breaking. Version and deprecate deliberately.
  • Design errors with stable codes, clear messages and one consistent shape.
  • Idempotent operations, or idempotency keys, make retries safe.
  • Keep contracts as data (schemas) so tools can validate requests and detect breaking changes.

Next: Technical Debt and Refactoring.