My account

API design

An API is a contract with people you may never meet. Use resources and HTTP methods in the normal way, return honest status codes, page through big lists, and change the API without breaking the clients that already use it.

Not reviewedWritten with AI helpReading time: 15 minOnline shop exampleHTTP and JSON

Author: bezzad

Contents

The problem: a small change breaks a partner

Our online shop has an API. The mobile app uses it, and so do three partner companies. One day a developer makes a “small” clean-up. They rename one field in the order response:

// Before
{ "id": 42, "total": 59.90 }

// After
{ "id": 42, "totalPrice": 59.90 }
  1. Our own tests pass, because we changed the tests too.
  2. The next morning, a partner’s app crashes for all its users. Their code still reads “total”.
  3. The old app versions on users’ phones also break. Many people never update their apps.

Inside our code, a rename is cheap. In a public API, it is a breaking change. Clients we cannot see depend on every name, every type and every status code.

The rest of this lesson shows how to design an API that is easy to use, and how to change it later without breaking anyone.

Resources and HTTP methods

A REST-style API is built around resources: the “things” of the business, like orders, products and customers.

  1. The URL names the thing. Use nouns, usually plural: /orders, /orders/42, /customers/7/orders.
  2. The HTTP method says the action. GET reads, POST creates, PUT replaces, PATCH changes a part, DELETE removes.
  3. So do not put verbs in the URL like /getOrders or /createOrder. The method already says it.
RequestPOST/v1/ordersIdempotency-Key: 7f3a9c{ "items": [...] }The actionWhich thingExtra informationThe dataResponse201 CreatedLocation: /v1/orders/42{ "id": "42", ... }The result, read firstWhere the new order isThe data
Every part of a request has one job. The status code is the first thing the client looks at.
Request Meaning Typical success code
GET /orders?status=paid List paid orders 200 OK
GET /orders/42 Read one order 200 OK
POST /orders Create a new order 201 Created
PATCH /orders/42 Change some fields of the order 200 OK
DELETE /orders/42 Delete the order 204 No Content
POST /orders/42/cancel An action that is not simple create, read, update or delete 200 OK

The last row is fine. Not every business action fits create, read, update and delete. “Cancel an order” has rules: refunds, stock, emails. A clear action URL is better than pretending it is a PATCH of a status field.

Safe and idempotent

Two words matter a lot when the network fails:

  1. Safe means the request does not change anything. GET is safe. A cache or a browser may send it again at any time.
  2. Idempotent means sending the same request twice has the same effect as sending it once. GET, PUT and DELETE are idempotent. POST is not.
  3. Why it matters: when a request times out, the client does not know if the server did the work. It can safely retry an idempotent request. A POST that is retried may create two orders.

The usual fix for POST is an idempotency key: the client sends a unique key with the request (often in a header called Idempotency-Key) and the same key on every retry. The server remembers the key and returns the first result. The Idempotency lesson explains this in detail.

Honest status codes

The status code is a standard contract. Libraries, caches, load balancers and monitoring tools read only the code, never the body. If every response is 200, they all believe everything worked.

  1. 2xx: success. 200 OK, 201 Created, 204 No Content.
  2. 4xx: the client made a mistake. Sending the same request again will not help. 400 bad request, 401 not logged in, 403 not allowed, 404 not found, 409 conflict with the current state, 422 the data is not valid.
  3. 5xx: the server has a problem. Trying again later may work. 500 unexpected error, 503 temporarily unavailable.

Give errors one shape across the whole API. The Problem Details standard (RFC 9457) gives a simple one:

HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json

{
  "type": "https://api.shop.example/errors/validation",
  "title": "The order is not valid.",
  "status": 422,
  "errors": { "quantity": ["Must be between 1 and 10."] }
}
Do not leak inside details. An error body is for the client. Do not put stack traces, SQL or server names in it. Log those on the server, and return a short message and maybe an id the client can give to support.

Big lists: pagination

GET /orders must not return all one million orders. Memory, time and network all grow with the table. Return pages, and set a maximum page size that the client cannot go over.

There are two common ways:

  1. Offset pagination. “Skip 1,000 rows, give me 50.” It is simple, and you can jump to any page. But the database still reads and throws away the skipped rows, so deep pages are slow. And if a new order arrives while a user moves between pages, items move: one item is shown twice, or one is skipped.
  2. Cursor pagination (also called keyset pagination). “Give me 50 orders after this one.” The server sends a cursor, a small token that says where the last page ended. With an index, every page is fast, and new rows do not move items between pages. But you cannot jump to page 2000.
Offset: skip 1,000, take 501,000 rows are read, then thrown away50 sentThe deeper the page, the more wasted work.Cursor: after the last item, take 50Not read50 sentThe index jumps straight to the place after the cursor.
Offset reads and throws away the rows it skips. A cursor starts reading right after the last item it sent.
GET /orders?limit=50&after=eyJpZCI6MTAyMzN9

HTTP/1.1 200 OK
Content-Type: application/json

{
  "items": [ ... ],
  "next": "eyJpZCI6MTAyODN9"
}
  1. The sort must be stable. Sort by a unique column, or add the id as a tie-breaker. Otherwise two orders with the same date can swap places between pages.
  2. The cursor is opaque. The client should not build it or read it. Then you can change what is inside it later.
  3. When next is empty, there are no more pages.
Which one to choose? For an admin table where people jump to page 7, offset is fine if the table is not huge. For feeds, mobile apps that scroll, and partners that read everything, use a cursor.

Clear and boring data

A good API is boring. The client can guess how a new endpoint works because it looks like the others.

  1. One naming style. For example, camelCase for every field, everywhere. Do not mix total_price and totalPrice.
  2. Dates in one standard format, with the time zone: “2026-10-12T15:20:00Z”. Use UTC when you can.
  3. Money is not a float. Floating-point numbers cannot store 0.1 exactly. Send the amount as a string (“59.90”) or as an integer in the smallest unit (5990 cents), and always send the currency.
  4. Ids are strings if they can ever be big or not numbers. JavaScript cannot store very large integers exactly.
  5. Filters and sorting in the query string: /orders?status=paid&sort=-createdAt.
  6. Do not return everything you have. Every field you return is a field you must keep forever. Start small; adding later is easy.

Change without breaking

Clients update slowly, or never. So every change must be checked: will an old client still work?

Safe for old clientsBreaks old clientsAdd a new endpointAdd a field to a responseAdd an optional request fieldMake a request field optionalRemove or rename a fieldChange the type of a fieldMake a request field requiredChange a status code or a meaning
Adding is usually safe. Removing, renaming or changing the meaning is breaking.
  1. Safe changes: add a new endpoint, add a new optional field to a request, add a new field to a response.
  2. Breaking changes: remove or rename a field, change its type (number to string), make an optional field required, change what a field means, change a status code.
  3. Clients must also be tolerant. Ask clients to ignore fields they do not know. Then adding a field never breaks them.

When you really need a breaking change, make a new version and keep the old one running for a while:

  1. Put the version in the URL, like /v1/orders and /v2/orders. It is easy to see and easy to route. Some teams use a header instead; both work, pick one.
  2. Tell clients early, with a date when the old version will stop.
  3. Watch the logs. Before you turn the old version off, check who still calls it.
  4. Do not make a new version for every change. Most changes can be made in a compatible way.
Write the contract down. Describe the API in an OpenAPI file: the endpoints, the fields, the types and examples. Clients can read it and generate code from it. You can also check in CI that a change does not break the contract.

A quick checklist for review

  1. Names. Are the URLs nouns? Is the naming style the same as the rest of the API?
  2. Methods. Is GET free of side effects? Can a retried POST create a duplicate?
  3. Status codes. Does an error return 4xx or 5xx, not 200? Do all errors have the same shape?
  4. Lists. Is there a page size limit? Is the sort stable?
  5. Data. Dates with time zones? Money without floats?
  6. Compatibility. Will a client built for yesterday’s API still work today?
  7. Security. Can a user read or change only their own data? Is every input checked?

Common mistakes

Mistake Result The right way
Verbs in URLs, like /getOrders The API is hard to guess. Every endpoint looks different. Nouns in the URL. The method is the verb.
Always 200, with an error inside the body Monitoring shows 0% errors. Clients and caches do the wrong thing. Honest status codes and one error shape.
Returning all rows Slow responses and out-of-memory crashes as data grows. Pages, a maximum page size, filters.
Renaming a field “to make it clean” Partner apps and old mobile versions crash. Add the new field, keep the old one, retire it with a version.
Money as a float Rounding errors in totals. A string or an integer in cents, plus the currency.
Retrying POST without an idempotency key Duplicate orders and double payments. An idempotency key sent on every retry.
Stack traces in error responses Attackers learn about the inside of the system. A short message for the client. Details only in the server log.

Summary in six lines

  1. An API is a contract. Clients you cannot see depend on every name, type and status code.
  2. URLs name resources. HTTP methods say the action. GET, PUT and DELETE are idempotent; POST is not.
  3. Return honest status codes and one error shape, like Problem Details.
  4. Page through big lists. Prefer a cursor for big or fast-changing data, and always limit the page size.
  5. Keep data boring: one naming style, dates with time zones, money without floats.
  6. Adding is safe; removing or renaming breaks. For a real breaking change, make a new version and retire the old one slowly.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.