Backend Engineering
Designing API contracts that remain safe as teams scale
Versioning, validation, pagination and error semantics for services other teams can trust.
Williams Madu · · 13 min read
Practical lessons from engineering reliable HTTP interfaces: stable contracts, schema validation, pagination rules, consistent errors, versioning, and integration tests.
Start with the consumer's decision
A useful API contract starts with the action another developer or product screen must complete. A response is not well designed because it mirrors database columns. It is well designed when consumers can answer what happened, what can be done next, and which fields are safe to rely on.
The same domain concept should use consistent names and shapes across endpoints. If a project has a slug, avoid introducing url_key in another response unless the distinction has a real meaning. Explicit optional fields are preferable to surprising nulls and undocumented fallback behavior.
- Define resources and operations in the language of the domain.
- Name required, optional and nullable fields separately.
- Agree on date formats, time zones and sorting behavior.
- Record error responses alongside success responses.
Validate at the trust boundary
Request validation belongs at the server boundary even when the frontend also validates forms. Clients can be outdated, misconfigured or intentionally malicious. The server must reject invalid states consistently before any lasting side effect occurs.
Choose response errors that are actionable without exposing implementation details. 400 can indicate malformed syntax, 401 missing authentication, 403 insufficient permission, 404 an unavailable resource, and 409 a business conflict. Do not reveal hidden records through different error wording.
- Parse and validate the input.
- Authenticate the caller and authorize the requested action.
- Apply domain rules and enforce uniqueness atomically.
- Execute side effects with idempotency where required.
- Return a minimal documented response and durable operation reference.
import { z } from 'zod'
const CreatePostInput = z.object({
title: z.string().trim().min(8).max(160),
slug: z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
category: z.string().trim().min(2),
})
const result = CreatePostInput.safeParse(body)
if (!result.success) return { status: 422, errors: result.error.flatten() }Illustrative validation at the API boundary; authorization and persistence still belong on the server.
Make pagination a predictable contract
Pagination is not just a row limit. The client needs the current page, total count where feasible, navigation flags, stable sorting and explicit bounds on requested page size. Unstable sorting can duplicate or omit records as items are created.
For large, frequently updated collections, cursor pagination may be more stable than numbered pages. For a modest blog index, numbered pages are easier for readers and search engines. The API should still clamp untrusted limits and provide a deterministic secondary sort key.
- Clamp limits to a documented maximum.
- Keep filters and sort order when navigating pages.
- Sort ties by a stable identifier.
- Test page boundaries and empty search results.
Evolve without silently breaking users
A contract change is breaking when an existing consumer must deploy new code to keep working. Renaming fields, changing types and changing the meaning of errors are obvious examples; subtle pagination or timezone changes can be equally disruptive.
Prefer additive changes, explicit deprecation windows and consumer-driven tests. When a breaking redesign is necessary, version the contract intentionally and measure adoption before withdrawing the previous route.
A well-designed contract optimizes for safe change by people who were not present when it was written.
Treat errors as product states
Network errors, validation failures and authorization boundaries become visible in the product interface. If an endpoint returns an ambiguous message, every frontend team must invent its own interpretation and recovery behavior.
Standardize a small error envelope with a machine-readable code, plain-language message, reference ID and optional field validation details. Keep internal stack traces in protected telemetry.
Further reading and references:
Build evidence into integration tests
Unit tests prove helpers and validators in isolation. Integration tests prove that serialization, permissions, database constraints and routing work together. Both are necessary when several teams depend on the same API.
Test a published resource, a hidden draft, an invalid page, unknown identifiers, concurrent updates and malformed filters. Capture representative response fixtures, and make backward compatibility part of code review rather than a manual afterthought.
- Positive and negative permission tests.
- Pagination boundary and deterministic ordering tests.
- Malformed input and resource-not-found tests.
- Contract shape and compatibility checks.
- Observability IDs in unexpected-error responses.