An API version without copying the entire application

Two response formats over one read: preserve the old contract, check consumers and prepare a transition.

Two external representations sharing one foundation: a conceptual illustration of API versions.
Two external representations sharing one foundation: a conceptual illustration of API versions.

A client reads readingSeconds, divides it by 60 and displays a reading duration. In the next release, the server returns a more convenient readingTime object. For the server, this is a small structural change; for an installed client, a required field has disappeared. Copying the controllers, reading rules and storage into a v2 directory alongside the new response would turn the compatibility problem into the maintenance of two applications as well.

An external contract version can be much smaller than an application. Consider one operation that estimates a note’s reading duration and two ways to represent its result. The inputs are fictional; reading speed is an exercise parameter, not a universal human characteristic. The PHP code was executed and added to one Symfony application. Twenty-two independent local scenarios passed; real kernel routes and the Symfony serializer were also checked. The results describe this synthetic contract, without a production API or network experiment.

Define what the client was promised first

The old contract returns id, title, a nonnegative integer readingSeconds, and one of two states: ready or empty. Duration is measured in seconds, rounded up. A client can rely on the type, unit and allowed values even if the server stores the information quite differently.

Google’s AIP-180 guidance distinguishes source, wire and semantic compatibility. These provide three useful questions for our exercise: can the client read the response, understand its shape and still obtain the result the consumer expected? The guidance has its own context; the product contract still defines the specific promise.

A library release, a database schema version and an API version are separate decisions. Replacing an internal repository does not require /v2 if external behavior is preserved. Renaming a response field may require a transition even when the database and all dependencies remain unchanged.

One operation computes the value

For note-17, the inputs specify 240 words and a rate of 240 words per minute. The expected duration is 60 seconds. For 241 words at the same rate, it is 61 seconds after rounding up. Empty text produces zero and the empty state; that is a valid result, not a missing record.

One EstimateReader reads and validates the synthetic data and creates a ReadingEstimate. This is where the rounding rule belongs. The V1Output and V2Output projectors receive seconds that have already been calculated. They do not calculate them again or independently decide whether an unpublished note may be shown.

The exercise bounds the word count and rate so that integer arithmetic remains well defined. With a positive divisor, the rule can be written as intdiv(words * 60 + rate - 1, rate). This is an estimate from the chosen model. It does not measure a particular reader’s actual time or account for text complexity, illustrations or interruptions.

The separation helps when correcting a mistake: fix a rounding error in one place, then check both external representations. If each version contained its own formula, a new format could silently introduce a new domain rule.

Two representations of one result

For the first synthetic record, the old contract has this shape:

{
  "id": "note-17",
  "title": "Calm Water",
  "readingSeconds": 60,
  "state": "ready"
}

In the second format, duration becomes a separate object with an explicit unit:

{
  "data": {
    "id": "note-17",
    "title": "Calm Water",
    "readingTime": {"value": 60, "unit": "second"},
    "state": "ready"
  }
}

This shape is deliberately incompatible. An old client must not accidentally receive it when selecting the old version. Both formats still describe the same note and the same duration. The new data envelope does not create a new entity or require a second table.

The adapter selects a representation after one domain read:

$body = match ($version) {
    'v1' => (new V1Output($estimate))->toArray(),
    'v2' => (new V2Output($estimate))->toArray(),
};

Before reaching this point, the adapter accepts only v1 or v2. An unknown latest selection produces a defined refusal before reading. An implicit switch to the “newest” version would make an unchanged request depend on when deployment occurred.

In API Platform, separate input and output DTOs help describe operation representations. In this exercise, the DTOs and version selection deliberately have no framework dependency. Integration must connect them to the existing routes and serialization, with real HTTP responses checked separately.

An added field is compatible only under a particular agreement

The first format could gain summary without changing its old fields. One client selects only the keys it needs and continues to work. Another compares the complete set of fields against a closed schema and rejects the response.

JSON Schema defines a separate rule for additional properties; additionalProperties: false prohibits them in the relevant schema context. Consequently, “we only added a field” does not describe the consequences for every consumer.

The exercise contains two prepared old clients with identical requirements for known fields. The first ignores unknown keys. The second also requires an exact set. A response containing summary should be accepted by the first and rejected by the second. This demonstrates the boundary of our agreement; it does not establish the behavior of every language SDK.

The policy for unknown fields should be specified before clients start depending on the API. If the contract already promised a closed response, an announcement cannot change a strict client’s behavior. A compatible format, a coordinated client update or a separate version is needed. A new required request field is a different situation: the old client does not even know that it must send it.

The type survives while the meaning breaks

The most visible changes are easy to present in a table. These expectations concern our particular old client.

Response change Consequence
title is renamed to name A required field is missing
readingSeconds is removed The duration cannot be read
The number 60 becomes the string "60" The expected type is violated
Required title becomes null The allowed set of values is violated
estimated is added to the states A client with a closed list rejects it
readingSeconds contains 60000 milliseconds The shape is acceptable, but the meaning is wrong
JSON object property order changes The values are the same for the prepared clients

The final numeric example matters especially. The parser sees a nonnegative integer, so both old clients accept it. However, they display 1000 minutes instead of one. Type checking does not detect a substituted unit; an independent expectation for the specific result is necessary.

Changing the rounding rule can also change behavior without adding a field. For 241 words, the old contract promises 61 seconds. A response containing 60 seconds does not become compatible merely because it remains an integer. Whether this is a defect correction or a changed promise must be decided using the previous contract and actual consumers.

Freeze expectations from the client’s side

The prepared suite contains 22 scenarios. Three fixtures specify the expected responses of both versions and what the client should display. Eight changed responses cover an extra field, renaming, removal, type, null, a new state, the unit and property order. The remaining scenarios concern version selection, refusals, internal fields and invalid data.

Expected JSON documents are written separately from the projectors. If a test asks the same mapper to produce both the result and the “correct” response, a shared error can go unnoticed. Comparison checks types and values without making JSON object property order part of the contract.

There is also a consumer check: both versions must produce the same display for the same three notes. A separate case specifies successful parsing with a semantically incorrect display. The test must recognize that mismatch rather than expect a decoding error that does not exist.

What actually ran

The original native harness exited with code 0 after 22 named scenarios. Three literal response fixtures check both versions and their client displays. Eight mutations retained the specified outcomes: the tolerant client accepted an extra summary while the strict client rejected it; rename/removal/type/null/enum changes were rejected; the changed unit parsed, but the semantic oracle found 1000 minutes instead of 1; property order did not become a false regression. The other scenarios check version selection, refusals, and data boundaries.

The canonical Demo passed 4 PHPUnit tests with 57 assertions: one adapter reran the same 22 scenarios as a regression check, while three HTTP tests made 12 kernel requests. These are not 44 distinct native scenarios or network requests. Execution used PHP 8.5.12, Symfony 8.1, and PHPUnit 13.4.6; the canonical suite requires PHP 8.4.1. Other PHP versions were not run.

GET /lab/contracts/v1/notes/{id} and /lab/contracts/v2/notes/{id} use one reader. Six allowed reads returned exact literal JSON, application/json, and 200 through the actual Symfony SerializerInterface. Each request made exactly one domain read. Four hidden/missing requests across the versions returned the same 404 JSON with only error.code = not_found, also with one read each and no internal fields.

The unknown-version policy was frozen before execution: fallback GET /lab/contracts/{version}/notes/{id} returns 400 JSON unsupported_version before a domain read. POST to v1 returned framework 405 without reading; no separate JSON MIME is promised for this framework refusal. Existing protected routes remain intact. This public synthetic lab does not verify production auth, locale, quota, OpenAPI, cache isolation, or an actual sunset.

A version does not create a second set of permissions

In the synthetic read, unpublished and missing notes both produce not_found in both versions. internalMemo belongs to neither DTO. Changing its internal structure must not change the external responses.

This is a narrow visibility check. The exercise does not implement API keys, user permissions, quotas or caching. In a real composition, both operations must pass the shared admission rules before protected reads. Selecting a new format does not grant access to additional data.

The same principle applies to caching: if version responses differ, the representation key must include that choice. Two differently named routes cannot safely receive the same cached JSON under a note identifier alone. Checking the format and checking actual delivery remain separate parts of acceptance.

Ending support for an old contract

A separate version is not needed for every new field. API Platform describes gradual evolution with deprecated operations and properties as an alternative to multiplying versions. For our deliberately incompatible change, two representations let clients migrate at their own pace, but supporting both has a cost.

A transition plan starts with an inventory of consumers and a comparison of formats. It then needs migration examples, a period of simultaneous support, observation of old-operation usage and an agreed retirement criterion. Zero requests during a short window do not prove that a client running once a month no longer exists.

Deprecation in RFC 9745 signals deprecation; its date uses Structured Field Date syntax with @. Sunset in RFC 8594 signals the expected end of availability and uses HTTP-date. These are different signals. The headers do not perform migration or disable a route by themselves.

The exercise assigns no shutdown date and does not automatically disable v1. It provides a plan under which that decision could be made. What needs to be preserved is a sufficient boundary around the old contract: the shape, values, errors and behavior on which clients still depend.

  1. API An API response is not an Entity: designing an article card
  2. API Permission to act and permission to access data: two checks for one API request
  3. Conformance Deprecated now, removed later: managing a package API migration
  4. Platform Engineering Consumer contract tests: catch a break before upgrading the site

A project by the author · Weather Solution200

After reading, a look outside.

Temperature, rain and wind in your city. Check the forecast and plan the hours ahead.

Check the forecast
Next article