Luke Vear

API Time Travel: Reverse-Migrating Responses for Old Clients

A small response-transformation pipeline that lets older clients keep their expected API shape as the backend evolves

Luke Vear
4 min read
API transformation layer adapting responses for older clients based on the requested version.
View full-size image

An immovable object meets an unstoppable force

Mobile applications are like a bad joke at a dinner party - once it’s out, you can’t take it back. Coordinating backwards-incompatible changes to the endpoints and schemas your mobile application consumes can be just as bad (or worse, as you can just leave a dinner party).

While we weren’t rolling out mobile applications at dinner parties, back in 2016 when YQueue was rolling out our mobile ordering application to our first customers, we received a feature request that would require us to make a backwards-incompatible change. Due to the team’s previous experience with API and mobile development, we obviously knew this would be required and preemptively added an X-API-VERSION header so we could implement our solution: time travel.

Transformers (not the AI kind)

Our API responses are piped through “transformers”. These are essentially responsible for taking an ORM entity, DTO, good old-fashioned array etc. and transforming it into a deterministic shape for the client. This pattern was very well established by 2016 so it was a no-brainer for us to adopt it. However, what was less clear was what we should do when we needed to change something about the shape. This could be as simple as changing something from an integer-backed value to a string, or something more complex like completely changing the shape to better suit updated requirements.

The pattern I settled on was to build the base response, then pass it through a series of transformation steps for older API versions. Each step adapts the response a little further back in time.

Here’s the relevant part of the implementation, using current PHP syntax. I’ve omitted the public entry points for individual models and collections:

abstract class AbstractTransformer
{
    /**
     * Retrieve the base representation of a transformed model.
     */
    abstract protected function getBaseData(mixed $model, ApiVersion $targetApiVersion): array;

    /**
     * The transformation steps that should be processed.
     */
    protected function steps(): array
    {
        return [];
    }

    /**
     * Processing the transformation of the model.
     */
    private function transform($model, ApiVersion $targetApiVersion): array
    {
        $data = $this->getBaseData($model, $targetApiVersion);

        /** @var TransformationStep[] $steps */
        $steps = array_map(
            function (string|object $step) {
                if (is_string($step)) {
                    return app($step);
                }

                return $step;
            },
            $this->steps()
        );

        foreach ($steps as $step) {
            if ($targetApiVersion->lte($step->apiVersion())) {
                $data = $step->transform($data, $model, $targetApiVersion);
            }
        }

        return $data;
    }
}

Each step declares the last API version that needs it. If the requested version is on or before that date, we apply the step to the response. Newer clients skip it. ApiVersion compares parsed dates, and app() resolves the step through Laravel’s container. Steps run in the order they’re declared, so ordering matters when two steps change the same field.

A practical example

Let’s assume that earlier mobile clients expected a user’s name to consist of a “first” and “last” name, such as:

{
  "name": {
    "first": "Barry",
    "last": "Barrington"
  }
}

Let’s then assume that we’ve read Falsehoods Programmers Believe About Names and realise that not everyone has a first and last name, so we decide to cut our losses and collapse names to a single field, such as:

{
  "name": "Dr. Barry Barrington III"
}

We can now implement our transformer, and transformation step, to ensure older clients receive the existing shape. Newer clients receive our flattened name (which we can just assume that we introduced in the API version that came after API_VERSION_22_01_2016).

class UserTransformer extends AbstractTransformer
{
    protected function getBaseData(mixed $model, ApiVersion $targetApiVersion): array
    {
        /** @var User $model */
        return [
            'uuid' => $model->uuid,
            'name' => $model->name,
            'created_at' => $model->created_at->toIso8601ZuluString(),
        ];
    }

    protected function steps(): array
    {
        return array_merge(parent::steps(), [
            LegacyNameSupport::class,
        ]);
    }
}
class LegacyNameSupport implements TransformationStep
{
    public function transform(array $data, $model, ApiVersion $apiVersion): array
    {
        $data['name'] = [
            'first' => explode(" ", $model->name)[0],
            'last' => implode(" ", array_slice(explode(" ", $model->name), 1)),
        ];

        return $data;
    }

    public function apiVersion(): ApiVersion
    {
        return new ApiVersion(Constants::API_VERSION_22_01_2016);
    }
}

For 22-01-2016 and earlier, the step turns Dr. Barry Barrington III into:

{
  "name": {
    "first": "Dr.",
    "last": "Barry Barrington III"
  }
}

Barry has apparently been promoted to having a first name of “Dr.” - congrats Barry!

This keeps the old response shape intact, but splitting a string cannot recover the original name parts. It’s a compromise for the older client, and exactly the sort of assumption we’re trying to retire. Newer versions skip the step and receive the full name as a string.

Why bother?

The nice part is that the API developer can generally concentrate on the most recent version when implementing a feature. If it breaks an older response contract, they add a transformation step and test both shapes. After that, the existing steps keep doing their job as the API evolves, and the older versions just “magically work”. The magic is, as one would expect, still code we have to maintain and test.

Transformers also call other transformers. For example, an order transformer can include a customer using the same UserTransformer:

class OrderTransformer extends AbstractTransformer
{
    protected function getBaseData(mixed $model, ApiVersion $targetApiVersion): array
    {
        return [
            'uuid' => $model->uuid,
            'customer' => app(UserTransformer::class)->transformModel(
                model: $model->customer,
                targetApiVersion: $targetApiVersion
            ),
        ];
    }
}

Passing the requested version down means the customer gets the same compatibility treatment whether it’s returned by itself or inside an order. We don’t have to remember to reimplement the name transformation in every endpoint that happens to include a user. That reuse is what lets backwards compatibility propagate through the API surface.

More generally, transformers give us an explicit boundary between our internal models and the public response. Adding a database field doesn’t automatically add it to the API, and reorganising a model doesn’t have to change what clients receive. The mapping and its compatibility steps can also be tested directly, wherever they’re reused.

There are limits to the magic: this pipeline adapts responses. Changes to incoming requests or business behaviour still need their own compatibility decisions.

Does time travel really work?

In the context of APIs - yes!

We’ve been using this approach since 2016. It’s seen us through hundreds of breaking API changes, and the original transformer infrastructure is still running in our codebases today. It’s had a few PHP syntax upgrades along the way, but the underlying approach hasn’t changed.

Know someone who would enjoy this?

View Markdown