Mosmoxmosmox

Mosmox journal

In focus — API.

A selection of publications grouped under the API tag.

Designing an API for Mobile Clients: Pagination, Versioning and Errors

Designing an API for Mobile Clients: Pagination, Versioning and Errors

A web client and its backend usually update together: you deploy and every user gets the new version. Mobile does not work that way. Production runs versions released eighteen months ago, devices on flaky 3G in the underground and users who switched off automatic updates. An API designed "as if for a website" becomes a constant source of crashes and client-side workarounds.

This article covers the three areas where mobile specifics bite hardest: pagination, versioning and error format. Plus idempotency, caching and the team contract, without which the first three do not hold up.

How a mobile client differs from the web

FactorWebMobile appImplication for the API
Client versionsOne currentDozens at onceBackward compatibility is mandatory
NetworkMostly stableDrops, high latency, Wi-Fi/LTE handoversIdempotency, retries, small responses
UpdatesInstantThrough review and the userKeep changeable logic on the server
ResourcesDesktop-classBattery, data, memoryFewer requests, compact payloads
LifecycleTab stays openApp is suspended and killedState restoration, reloading pages

The core rule: every API change must be safe for the oldest supported app version. Google formalises what counts as a breaking change in AIP-180: removing or renaming a field, changing a type, adding a required request field, changing defaults.

Pagination: cursors instead of pages

Offset pagination (?page=3&limit=20) is simple, but in mobile feeds it causes two classic bugs. If a new order arrives between loading page one and page two, the user sees a duplicate. If a record is deleted, an item disappears. And large offsets are slow at the database level.

Cursor (keyset) pagination passes an opaque position token: the client receives next_cursor and sends it with the next request. Google recommends this approach in AIP-158 (page_token), and for GraphQL it is standardised in the Relay Connections specification.

CriterionOffset / pageCursor (keyset)
Stability under inserts and deletesDuplicates and gapsStable
Performance on deep pagesDegrades as offset growsStable with an index
Jump to arbitrary pageYesNo (rarely needed in mobile feeds)
Total countEasySeparate, ideally cached request
Implementation effortMinimalModerate

Practical rules

  • Keep the cursor opaque (for example, base64 of the id and sort date) so you can change the implementation without touching clients.
  • The server sets the maximum page size; the client may ask for less. For mobile lists, 20–50 items is usually enough.
  • Return an explicit end marker: an empty next_cursor or has_more: false.
  • For pull-to-refresh, support fetching items newer than the first one instead of reloading the whole list.
  • Make sorting deterministic, "by date, then by id", or records with identical dates shuffle between pages.

Versioning: not breaking old apps

There are three common approaches: version in the URL (/v2/orders), in a header (Accept or a custom one), or dated versions as at Stripe, where each client is pinned to a specific API date. For most mobile products we recommend the simple path: a major version in the URL and as many additive changes within it as possible.

Additive changes are safe

  • A new optional response field. The client must ignore unknown fields: verify your JSON decoder does not choke on them (in Swift Codable and kotlinx.serialization this is a configuration choice, not universal default behaviour).
  • A new endpoint or a new optional query parameter.
  • A new enum value, but only if the client maps unknown values to "unknown" instead of crashing.

Version support policy

  1. The client sends its app version and platform with every request (for example, an X-App-Version header). That gives you statistics and the option to vary behaviour selectively.
  2. Define a minimum supported version and a window, for example versions from the last 12 months.
  3. Implement soft and hard update prompts: a config endpoint returns min_supported and recommended versions. Android offers the In-App Updates API; on iOS, a custom screen linking to the App Store.
  4. Before retiring an old API version, check its share of traffic. We usually wait until it falls below 1–2% of active users and announce the forced update in advance.

Errors: one format for the whole API

The worst variant, which we see regularly: 200 OK with {"success": false} in the body, different error shapes per endpoint, and English text the client shows to users verbatim. RFC 9457 Problem Details (the successor to RFC 7807) defines a single structure: type, title, status, detail, instance plus custom extensions.

What a mobile client needs from an error

  • The correct HTTP status per RFC 9110: 400/422 for invalid input, 401 for missing authentication, 403 for missing permission, 404 for a missing resource, 409 for a conflict, 429 for too many requests, 5xx for server problems.
  • A machine-readable code (type or code) the client uses to decide what to do: show an inline error, offer a retry or sign the user out.
  • Per-field validation errors so a specific form field can be highlighted.
  • A request id for log lookups when the user contacts support.
  • Localised text, either via Accept-Language or on the client by code. What matters is that ownership is clear.
SituationStatusClient behaviour
Invalid e-mail in a form422 + per-field errorsHighlight the field, do not retry
Expired access token401Refresh the token and retry once
Item sold out during checkout409 + out_of_stock codeShow a dialog and refresh the cart
Rate limit exceeded429 + Retry-AfterWait the given time, show a message
Server failure500/503Retry with exponential backoff, show cached data

Idempotency and unreliable networks

The user taps "Pay", the request reaches the server, and the response is lost in a tunnel. The client retries and creates a second order. The fix is an idempotency key: the client generates a UUID for the operation and sends it in an Idempotency-Key header; when the server sees a retry with the same key, it returns the stored result. This is how the Stripe API works, and the header is being standardised at the IETF.

GET, PUT and DELETE are idempotent by definition; POST is not. So keys matter most for creating orders, payments, messages and any money-related operation.

Performance: fewer requests, fewer bytes

  • Aggregate data per screen. If the home screen makes eight requests at launch, consider an endpoint that returns everything in one call (the Backend for Frontend pattern).
  • Conditional requests. ETag and If-None-Match let the server reply 304 Not Modified without a body.
  • Compression. gzip or brotli shrinks JSON several-fold.
  • Image size. Serve URLs with size parameters, not multi-megabyte originals.
  • Timestamps. All dates in ISO 8601 with a time zone (UTC); formatting happens on the client.

The contract between backend and mobile teams

An OpenAPI description is not box-ticking documentation but a contract. From it you can generate client code, a mock server so mobile developers do not wait for the backend, and contract tests that catch breaking changes in CI. A practice that works well in our projects: every schema change is reviewed by a mobile developer, and CI automatically diffs the new schema against the previous one and blocks field removals.

Common mistakes

  • Renaming a field "because it reads better" without a new API version.
  • Offset pagination in frequently updated feeds.
  • Errors returned with status 200, and different error formats per endpoint.
  • No forced-update mechanism in the first release: you cannot retrofit it into old versions later.
  • Retrying POST requests without an idempotency key.
  • A client decoder that crashes on an unknown field or enum value.

API checklist before release

  1. Cursor pagination with deterministic sorting and an explicit end marker.
  2. A documented versioning policy and minimum supported app version.
  3. A config endpoint with a min_supported version in the very first release.
  4. A single error format (RFC 9457), machine-readable codes, request ids.
  5. Idempotency-Key for every non-idempotent money or order operation.
  6. The client ignores unknown fields and handles unknown enum values.
  7. OpenAPI schema in the repository, backward-compatibility checks in CI.
  8. ETags, compression and aggregated endpoints for key screens.

Sources: RFC 9457: Problem Details for HTTP APIs; RFC 9110: HTTP Semantics; Google AIP-158: Pagination; Google AIP-180: Backwards compatibility; GraphQL Cursor Connections Specification; Stripe: API versioning; Stripe: Idempotent requests; IETF: The Idempotency-Key HTTP Header Field; OpenAPI Specification; Android: In-app updates.

Journal

Ideas and products