What you'll learn: By the end of this lesson you will be able to say what an API contract promises and what it cannot, explain why TypeScript types alone do not protect a client at run time, apply the tolerant-reader rule (ignore what you do not need, fail on what you do), check an untrusted payload once at the edge, and map wire values (names, money, dates, nulls, unknown enum values) to the application's own types, with a tested function and twelve example payloads.
A customs office sits between two countries. Goods arrive in foreign packaging, with labels in another language and weights in other units. The office checks that the shipment matches the paperwork, and repackages it for the local shops. Shops never see the foreign boxes. A front end's edge does the same for an API: it checks that the data matches what was promised and repackages it into the application's own shapes, so components never touch raw wire data.
API Integration Basics covered how a call is built and how it fails. This lesson is about the successful response: a 200 whose body is a promise you must check before relying on it.
The core idea
A contract is the set of promises two sides rely on: which fields exist, their types, which may be absent or null, which values an enum may take, how errors look, and what may change without warning. A transformation is the code that turns the wire's version of the data into the application's.
Three jobs sit at the edge, and the lesson is their order:
- Check. Is this payload what the contract says? If not, fail with a path to the problem.
- Translate. Convert wire names and encodings to domain types: snake_case to camelCase, integer cents to a money value, date strings to dates.
- Tolerate. Accept the changes the contract allows (a new field) and decide ahead of time what to do about the ones it does not (an unknown enum value).
Figure 1. The edge between wire data and the application
How to read this: raw JSON enters on the left as unknown. Only values that pass both steps reach the application. A failure leaves through the bottom, carrying paths such as $.price_cents.
What a contract holds, and what it cannot hold
| Part of the contract | Question a client needs answered | Typical trap |
|---|---|---|
| Shape | Which fields exist, and which are required? | A required field renamed |
Optional vs null |
Absent, null and a value are three states |
Treating them the same without saying so |
| Enums | Is the list of values closed or may it grow? | A new value crashes a switch |
| Formats | How are money, dates and ids encoded? | "12.50" where an integer was promised |
| Errors | What does a failure body look like? | Parsing prose instead of a stable member |
| Change rules | What may change without notice? | A new field breaks a strict reader |
JSON Schema, which OpenAPI schemas build on, draws the line on the first two rows: its documentation says properties are not required by default, that additional properties are allowed by default, and that in JSON a property with the value null is not equivalent to the property being absent.
A contract is written down in a specification, or in example payloads that both sides test (below), or both. It cannot promise that the server code actually behaves that way today. That is why a client checks at run time.
Types are claims, not proofs
TypeScript's handbook says a type assertion is "removed by the compiler", so "there is no runtime checking associated with a type assertion" and no exception if it is wrong. (await response.json()) as ProductDto therefore tells the compiler to trust you, and nothing else.
Illustration 1 (minimal example): a claim and a check
// A claim: compiles, checks nothing at run time.
const dto = (await response.json()) as ProductDto;
// A check: the value is `unknown` until it has passed the schema.
const result = readProduct(await response.json());
if (!result.ok) reportContractIssue(result.issues); // paths such as $.price_cents
reportContractIssue is a stand-in name. The second form is the lab's readProduct:
export function readProduct(raw: unknown): ParseResult<Product> {
const parsed = productDtoSchema.parse(raw);
if (!parsed.ok) return parsed;
return mapProduct(parsed.value);
}
It takes unknown, checks the shape against a schema, and only then translates. The lab's validator is a small hand-written one so the lab has no dependency; a real project would use a schema library or generate the schemas (the next lesson).
Tolerant reader: be liberal, but only where it is safe
Martin Fowler's Tolerant Reader advice is to be as tolerant as possible when reading data from a service: take only the elements you need, ignore everything else, assume as little as possible about structure, and keep the parsing in one place. The article names Postel's law, "be conservative in what you do, be liberal in what you accept from others", as the governing principle for decoupled collaboration.
Applied to a client:
- Unknown fields: ignore. A server adding
warehouse_codemust not break a reader that does not use it. The lab's schema drops unknown keys. - Missing or mistyped fields you use: fail. Being tolerant here would only move the crash to a component.
- Unknown enum values: decide a policy. The lab reads
statusas a string and maps anything it does not know to"unknown", so the page keeps working. A different product may prefer to fail. What matters is that the choice is written in one function.
Figure 2. How the edge treats each kind of change
How to read this: only the bottom two outcomes stop the page. The other three are changes a contract may make without telling clients, so the reader absorbs them.
Translation: the wire's words become the application's
Each translation in the lab is one decision.
- Names.
price_cents,in_stockandcreated_atbecomeprice,availableandaddedAt. Components never see snake_case. - Money. The wire carries integer minor units, and the domain carries a
Moneyvalue with a currency. A float is the wrong type for money: the lab's demo prints19.99 * 100 = 1998.9999999999998. Formatting uses integer arithmetic and a table of decimal places per currency; the lab's table gives yen none. - Dates. MDN says that when an offset is absent, date-only forms are read as UTC but date-time forms as local time, and that implementations behave inconsistently for a string like February 30. The lab requires an RFC 3339 date-time with an offset and checks that the calendar date exists. On Node 26.13.1,
new Date("2026-02-30T09:00:00Z")returns 2 March 2026 instead of an invalid date, so the explicit calendar check is needed. - Absent and
null. Both becomediscountPercent: nullin the domain; the lab decides this is one state ("no discount") and writes it once. - The other direction.
toUpdateRequestturns a domainMoneyback intoprice_cents, so the request body is the contract's shape too.
Figure 3. Absent, null and a value, read at the edge
How to read this: three wire states, two domain states, one failure. Writing the mapping down once is what keeps components from each inventing a meaning for undefined.
Illustration 2 (realistic example): a product page and twelve example payloads
A product page shows name, price, stock, an "added on" date and a status badge. The contract is a file of example payloads, one per documented outcome, each with the result the edge must produce. The same file is a test for the client now and can be replayed against the real server by a server-side test later.
Figure 4. One fixture file, two sides of the contract
How to read this: the client half runs in this lab. The server half is described but not built here; a contract is only two-sided when both halves exist.
Illustration 3 (failure case): the payloads that must not get through
The fixtures include the ways a response goes wrong: a price sent as the string "12.50", a required field renamed, null where the contract says never, a date without an offset, a discount of 150, and [] where an object was promised. Each must fail with a path, not produce a half-filled product. The demo below shows each result.
Build it: replay twelve payloads through one function
Goal. Run readProduct over twelve example payloads and see what the application receives for each, including the failures.
Setup. The lab is in the course's example workspace (Node 26, pnpm). The input is already-parsed JSON, so no fake fetch is needed.
cd examples/frontend
pnpm install
cd labs/api-contract-mapping
pnpm test # 23 tests in 2 files
node src/demo.ts
Steps.
- Run the tests.
contract.test.tsreplays every case offixtures/product.cases.json;mapper.test.tscovers dates, money, status and the request direction. - Run the demo and compare with the output below. Look at the additive field that vanishes from the result, the unknown status, the yen price, and the six failures with their paths.
Expected output, captured from a real run (Node 26.13.1, 2026-11-30):
=== full payload
payload: {"id":"p-100","name":"Trail mug","price_cents":1250,"currency":"EUR","in_stock":true,"created_at":"2026-03-01T09:00:00Z","discount_percent":10,"status":"active"}
result: ok {"id":"p-100","name":"Trail mug","price":{"minor":1250,"currency":"EUR"},"available":true,"addedAt":"2026-03-01T09:00:00.000Z","discountPercent":10,"status":"active"}
shown: 12.50 EUR, added 2026-03-01, status active
=== optional field absent
payload: {"id":"p-101","name":"Plain mug","price_cents":900,"currency":"USD","in_stock":false,"created_at":"2026-03-02T10:30:00+02:00","status":"active"}
result: ok {"id":"p-101","name":"Plain mug","price":{"minor":900,"currency":"USD"},"available":false,"addedAt":"2026-03-02T08:30:00.000Z","discountPercent":null,"status":"active"}
shown: 9.00 USD, added 2026-03-02, status active
=== optional field explicitly null
payload: {"id":"p-102","name":"Cup","price_cents":405,"currency":"GBP","in_stock":true,"created_at":"2026-03-03T00:00:00.500Z","discount_percent":null,"status":"discontinued"}
result: ok {"id":"p-102","name":"Cup","price":{"minor":405,"currency":"GBP"},"available":true,"addedAt":"2026-03-03T00:00:00.500Z","discountPercent":null,"status":"discontinued"}
shown: 4.05 GBP, added 2026-03-03, status discontinued
=== additive change: a field this client does not know
payload: {"id":"p-103","name":"Bowl","price_cents":700,"currency":"EUR","in_stock":true,"created_at":"2026-03-04T12:00:00Z","status":"active","warehouse_code":"W-9"}
result: ok {"id":"p-103","name":"Bowl","price":{"minor":700,"currency":"EUR"},"available":true,"addedAt":"2026-03-04T12:00:00.000Z","discountPercent":null,"status":"active"}
shown: 7.00 EUR, added 2026-03-04, status active
=== a status value this client has never seen
payload: {"id":"p-104","name":"Flask","price_cents":2100,"currency":"USD","in_stock":false,"created_at":"2026-03-05T08:15:00Z","status":"preorder"}
result: ok {"id":"p-104","name":"Flask","price":{"minor":2100,"currency":"USD"},"available":false,"addedAt":"2026-03-05T08:15:00.000Z","discountPercent":null,"status":"unknown"}
shown: 21.00 USD, added 2026-03-05, status unknown
=== a currency with no minor unit
payload: {"id":"p-105","name":"Tea tin","price_cents":500,"currency":"JPY","in_stock":true,"created_at":"2026-03-06T08:15:00Z","status":"active"}
result: ok {"id":"p-105","name":"Tea tin","price":{"minor":500,"currency":"JPY"},"available":true,"addedAt":"2026-03-06T08:15:00.000Z","discountPercent":null,"status":"active"}
shown: 500 JPY, added 2026-03-06, status active
=== breaking change: price sent as a decimal string
payload: {"id":"p-100","name":"Trail mug","price_cents":"12.50","currency":"EUR","in_stock":true,"created_at":"2026-03-01T09:00:00Z","status":"active"}
result: error [{"path":"$.price_cents","message":"expected integer, got string"}]
=== breaking change: a required field renamed
payload: {"id":"p-100","name":"Trail mug","price_cents":1250,"currency":"EUR","available":true,"created_at":"2026-03-01T09:00:00Z","status":"active"}
result: error [{"path":"$.in_stock","message":"required property is missing"}]
=== null where the contract says never null
payload: {"id":"p-100","name":null,"price_cents":1250,"currency":"EUR","in_stock":true,"created_at":"2026-03-01T09:00:00Z","status":"active"}
result: error [{"path":"$.name","message":"expected string, got null"}]
=== a date without an offset
payload: {"id":"p-100","name":"Trail mug","price_cents":1250,"currency":"EUR","in_stock":true,"created_at":"2026-03-01T09:00:00","status":"active"}
result: error [{"path":"$.created_at","message":"expected an RFC 3339 date-time with an offset, such as 2026-03-01T09:00:00Z"}]
=== a discount outside 0 to 100
payload: {"id":"p-100","name":"Trail mug","price_cents":1250,"currency":"EUR","in_stock":true,"created_at":"2026-03-01T09:00:00Z","discount_percent":150,"status":"active"}
result: error [{"path":"$.discount_percent","message":"expected 0 to 100, got 150"}]
=== not an object at all
payload: []
result: error [{"path":"quot;,"message":"expected object, got array"}]
=== request direction: domain to wire
{"name":"Trail mug","price_cents":1999,"currency":"USD"}
=== why money is an integer
19.99 * 100 = 1998.9999999999998
Math.round(19.99 * 100) = 1999
The result lines show the application's shape, not the wire's: price is an object with minor and currency, addedAt is a date printed as ISO 8601 in UTC, and the +02:00 input became 08:30:00.000Z.
What the lab does not show. No fetch, no React and no real server. The validator is hand-written and small; the mapping policies are this lab's choices, not rules. Only the four currencies in the table are handled.
Break it. In a scratch copy, make mapStatus return its input unchanged. The fixture for a status the client has never seen fails, because the domain object now carries "preorder" although its type says it cannot. Restore it afterwards and run the tests again.
In practice: a price field changes shape
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
A shop sells in three currencies and is adding a fourth, one with no minor unit. The catalogue team wants to send prices as decimal strings, because "the fourth currency does not fit cents". The front end has six components that read price_cents, two of which divide by 100.
Starting architecture
Components read the response directly and format with price_cents / 100. The response type is a hand-written interface and a type assertion.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Change every component | Handles the new field | Six edits | Each edit can be wrong, and old bundles break anyway |
Edge mapper with a Money domain type |
One place knows the encoding | A day, plus tests | Needs agreement on the contract |
Ask the server to keep price_cents and add a field |
Old clients keep working | A server change | Two fields to keep consistent |
The decision
| Field | Decision record |
|---|---|
| Context | A price encoding is changing; many readers; old bundles stay open for days. |
| Decision | Add an edge mapper producing Money. The server adds new fields and keeps the old one until old bundles are gone; the client ignores fields it does not use. Fixtures hold a payload for each currency and for each failure. |
| Consequences, good | Components never see encodings; a contract break fails with a path, in tests and in logs. |
| Consequences, bad | The mapper is a place that must be kept up to date with the contract. |
| Revisit when | The contract is generated from a specification, which the next lesson covers. |
Rollout and verification
- Fixtures first. Add a payload for the new currency and one for the old encoding, and make the mapper pass both.
- Ship the mapper behind a flag and compare the count of contract failures with the baseline.
- Test the failures. A string price, a missing field and an unknown status each fail or map as written.
- Log the paths. A contract failure with a path tells the server team which field moved.
The 2 a.m. failure
Order dates on the account page are a day off for users in some regions, and the server's own checks are green. A backend service started sending created_at without a time zone offset. The old client built dates with new Date(value): MDN says date-time strings without an offset are read as local time, so the same string means different instants in different regions.
First three checks: (1) compare the raw created_at of an affected order with what the page shows; (2) check whether the string has an offset; (3) check which services changed in the last release. Mitigation: ask the server to send an offset, and make the edge reject strings without one so the failure is loud. Follow-up: add a fixture for a date without an offset, and an alert on contract failures per path.
The other side of this topic
The server owns the contract: it decides what is required, nullable and versioned, and it must keep the promises it publishes. The back-end view is in API Styles: REST, gRPC, GraphQL and WebSockets and System Design: API Design. A front end reads those promises as the list of things it must check.
Trade-offs
| Choice | Gains | Costs |
|---|---|---|
| Type assertion only | No code | No run-time protection; failures appear in components |
| Hand-written edge mapper | Full control; domain types | Must be kept in step with the contract |
| Generated types and schemas | Less drift | Needs a good specification; policies still need writing |
| Strict reader (fail on any difference) | Drift found early | Breaks on harmless additive changes |
| Tolerant reader | Survives additive changes | Can hide drift unless dropped keys are reported |
Architect's notes
- Validate once, at the edge. Not in each component.
- Make absent,
nulland unknown values explicit policies. Write each in one place. - Report dropped keys and contract failures to monitoring. Tolerance without a signal hides drift.
- Keep fixtures as the shared language between client and server teams.
Common mistakes
asinstead of a check. It silences the compiler and checks nothing.- Using floats for money. Keep integer minor units and a currency.
- Parsing dates without an offset. The same string means different instants.
- Crashing on an unknown enum value. Decide a policy ahead of time.
- Validating in every component. Do it once, at the edge.
Key takeaways
- A contract is a set of promises; the client checks them at run time because a type cannot.
- Tolerant reader: ignore what you do not use, fail on what you do, keep the parsing in one place.
- Absent,
nulland a value are three wire states; map them to the domain on purpose. - Translate names, money and dates at the edge, in both directions.
- Unknown enum values need a written policy.
- A shared fixture file turns a contract into tests.
Practice exercises
Exercise 1: Starter (30 min). Take one API response in a project. List each field's type, whether it may be absent or null, and what the UI does today when it is wrong.
Exercise 2: Intermediate (2 hours). Write a read function for that response taking unknown, returning a value or issues with paths. Add ten fixture payloads, including three that must fail.
Exercise 3: Advanced (half day). Add a second version of one field to the fixtures and make the mapper accept both. Report a metric when the old form is seen, and decide when it can be removed.
Related reading
In this course:
- API Integration Basics: Fetching, Headers and Failure, the call and its failure kinds.
- Consuming REST, GraphQL and tRPC from a Client, where types come from in each style.
- Ports and Adapters in the Front End, putting the edge behind an interface the application owns.
- Form State and Validation, validation of what the user types, the mirror image of this lesson.
Next in this module: From OpenAPI to TypeScript contract types.
Official documentation
- TypeScript handbook: Everyday Types, type assertions and optional properties.
- JSON Schema: object, required properties, additional properties and
null. - MDN: Date, the date time string format.
- Martin Fowler: Tolerant Reader
- RFC 9457: Problem Details for HTTP APIs