How to Verify an API Rewrite With Differential Testing

Rewriting an API? Learn how differential testing API rewrites against the old service catches the bugs your test suite misses before cutover.

Ashley Innocent

Ashley Innocent

26 November 2026

How to Verify an API Rewrite With Differential Testing

Apidog for Enterprise

On-Premises Deploy

SSO & RBAC

SOC 2 Compliant

Explore Apidog Enterprise

Differential testing an API rewrite means you send the same requests to the old service and the new one, normalize the fields that are allowed to differ, and diff everything else: status codes, headers and bodies. The old service is your oracle. Any difference it can’t explain is a bug in the rewrite, or a behavior your users depend on that nobody wrote down.

Anthropic just showed why this matters. When it moved its Messages API from Python to Rust, the Rust version passed about 98% of its tests in April, yet only about a quarter of inputs matched on production traffic. The tests had also drifted: an audit of the ported suite found more than 100 weakened assertions. The fix was to stop trusting the suite and compare the new service against the old one.

You can do the same for your own language port, framework swap or monolith split. Here’s the method, the fields to ignore, and how to hand the comparison to your coding agent.

What is differential testing for an API rewrite?

Differential testing feeds identical inputs to two implementations of the same behavior and flags any output that differs. For an API rewrite, the old service defines “correct”, the rewrite is the candidate, and a mismatch in status, headers or normalized body is a finding to explain or fix before cutover.

It answers a different question from your other tests:

Test type Question it answers Source of “correct”
Unit and integration tests Does the code do what we wrote down? Assertions someone wrote
Contract testing Does the response match the spec? OpenAPI or a consumer contract
Regression testing Did this change break what used to pass? Last green run
Differential testing Does the new service behave like the old one? The old service itself

Why your test suite isn’t enough to verify a rewrite

The existing suite falls short in three ways:

The old service already encodes every one of those behaviors. Differential testing turns it into the test.

Shadow traffic vs replayed fixtures

There are two ways to feed both services the same requests. Start with replay; add shadowing once the replay diff is quiet.

Replayed fixtures Shadow (mirrored) traffic
Input A saved corpus of real or synthetic requests A copy of live production requests
Where it runs Staging, CI, a laptop Production, out of band
Coverage What you captured Whatever users actually send
Side effects Easy to isolate with test data Writes must be blocked or sandboxed
Repeatable Yes, same corpus every run No, traffic changes daily
Best for Fast inner loop, CI gate Finding the long tail before cutover

Shadowing usually lives in your proxy or mesh. Istio’s traffic mirroring sends each request to a second service “fire and forget” and discards the mirrored response, so users only see the old answer. Your differ has to capture both responses itself.

Shadow traffic: the proxy serves users from the old service and mirrors each request to the rewrite, whose response goes only to the differ.

For a single code path, GitHub’s Scientist library does the same in-process: it runs old and new, returns the old result and publishes the comparison.

How to run a differential test on an API rewrite

  1. Build a request corpus. Sample real requests from access logs, strip secrets and personal data, and add edge cases: empty bodies, unicode, maximum lengths, every error path.
  2. Send each request to both services against the same data. If they read different databases, they’ll disagree on everything.
  3. Normalize volatile fields such as ids, timestamps and request ids (next section).
  4. Diff in layers. Status code, then chosen headers, then the parsed body. Key order and whitespace aren’t behavior, so diff JSON, not text.
  5. Fingerprint and group. One bug can cause thousands of identical mismatches. Group by endpoint, the JSON path of the first difference and the kind of change.
  6. Fix, then rerun the whole corpus. One fix often reveals a bug it was hiding.
Sequence diagram: a replay harness sends each request to the old and new services, masks volatile fields, diffs the responses and groups mismatches.

A minimal differ for step 4 fits in a few lines of Python:

import re

VOLATILE = {"id", "created_at", "updated_at", "request_id", "etag"}
UUID = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")

def normalize(value):
    if isinstance(value, dict):
        return {k: "<volatile>" if k in VOLATILE else normalize(v) for k, v in value.items()}
    if isinstance(value, list):
        return [normalize(v) for v in value]
    if isinstance(value, str):
        return UUID.sub("<uuid>", value)
    return value

def compare(old, new):
    diffs = []
    if old.status_code != new.status_code:
        diffs.append("status")
    for h in ("content-type", "location"):
        if old.headers.get(h) != new.headers.get(h):
            diffs.append(f"header:{h}")
    if normalize(old.json()) != normalize(new.json()):
        diffs.append("body")
    return diffs

In the shell, jq can do the same normalization with walk and del.

Which fields to ignore when you compare old and new APIs

Ignore as little as you can: every masked field is a place a bug can hide.

Field Why it differs How to handle it
Generated ids (id, UUIDs) Each service mints its own Mask the value, keep the type and position
Timestamps Clock and timing Mask, or allow a small window
Date, Server, X-Request-Id headers Per-response Exclude from the header diff
ETag, signatures Derived from volatile bytes Exclude or recompute
Array order Only if the API never promised an order Sort before comparing, and document why
Floats Rounding across languages Compare with a tolerance

Be careful with automatic noise detection. Diffy runs two copies of the old service to learn which fields are noise, which works well for deterministic APIs. Anthropic noted the trap: when output legitimately varies, that approach ignores the field and any bug inside it.

Side effects and nondeterminism

Data flow: a nondeterministic value is generated once and replayed to both services, the rewrite writes only to sandboxed dependencies, and both outputs meet in the differ.

Let your coding agent run the comparison with Apidog CLI

Flow-level comparison is tedious by hand and easy to hand to an agent. Model your critical flows once as an Apidog test scenario with assertions, point two environments at the old and new base URLs, and let your coding agent run both and compare.

Set up Apidog CLI and the agent skill once:

npm install -g apidog-cli@latest
apidog login --with-token <YOUR_TOKEN>
npx -y skills add https://apidog.com   # pick your agent when prompted

Then give your agent one prompt:

In Apidog project <projectId>, find the environments for the old and the new
service. Run test scenario <scenarioId> against each one with cli and json
reports, then compare the two runs step by step: status codes, assertion
results and failures. Ignore generated ids and timings. List every difference.

The agent looks up the environment ids, then runs the same scenario twice:

apidog environment list --project <projectId>
apidog run --project <projectId> -t <scenarioId> -e <oldEnvId> -r cli,json --out-file old
apidog run --project <projectId> -t <scenarioId> -e <newEnvId> -r cli,json --out-file new

Add --branch <branchName> if the scenario lives on a sprint or AI branch. Here’s a real run on a sandbox project whose two environments hit the same public API: all 7 assertions passed on each side, and only the generated object ids differ.

Apidog CLI running one test scenario against two environments, with every check passing on both runs and only the generated object ids differing

The JSON reports hold run stats and failures, not raw bodies, so put what must match into the scenario’s assertions and use the Python differ for body-level parity. Once both sides agree, the same apidog run ... -r junit becomes your CI gate: see Apidog CLI in a CI/CD pipeline, the apidog run command reference and Apidog CLI in Claude Code.

Once a rewrite throws off dozens of diff fingerprints, you can file each one as a task on Sharkly, where your team’s coding agents pick them up in parallel on your own machines and you review each fix before it merges. It’s free to start.

When is the rewrite ready to cut over?

Set the bar before you start, so “good enough” doesn’t drift:

After cutover, keep the differ running with the roles swapped for a while. It’s the cheapest canary you’ll get.

FAQ

What’s the difference between differential testing and regression testing? Regression testing checks a version against assertions or a previous green run; differential testing checks it against another running implementation. A rewrite needs both: regression tests for known behavior, differential tests for what nobody wrote down.

Do I need production traffic to do differential testing? No. A replayed corpus plus edge cases runs anywhere and catches a lot. Shadow traffic adds the long tail you didn’t capture, so add it before cutover if you can isolate side effects.

How do I handle fields that are always different, like ids and timestamps? Mask the value but keep its key and type, so a missing or renamed field still shows up. Exclude per-response headers like Date.

Can I differential test an API whose responses are nondeterministic? Yes, if you isolate the nondeterministic part. Generate it once, replay the same value to both services, and compare everything around it exactly.

Is shadow traffic safe for write endpoints? Only if the candidate can’t reach real side effects. Point it at sandboxed dependencies or restrict shadowing to reads, and replay writes in staging.

Wrapping up

Your test suite knows what you wrote down; the old service knows what your users rely on. Capture a corpus, normalize carefully, diff in layers, group by fingerprint, and set the cutover bar early.

Explore more

Best OpenAPI TypeScript Client Generators in 2027

Best OpenAPI TypeScript Client Generators in 2027

We ran Kubb v5, Hey API, Orval and openapi-typescript on GitHub's 1,281-operation REST spec: generate time, output size, strict type-check results and runtime bytes, plus a pick-this-if table.

26 November 2026

How to Use 1Password Secrets in Your API Tests

How to Use 1Password Secrets in Your API Tests

Want 1Password CLI API testing without keys in your repo? Learn how op run feeds secrets to Apidog CLI, your coding agent and CI, fully masked.

26 November 2026

Anthropic Messages API Rust Migration: What Changed for Claude API Users

Anthropic Messages API Rust Migration: What Changed for Claude API Users

Wondering what the Anthropic Messages API Rust move means for your Claude calls? Learn what changed, what to re-test and how to measure TTFT.

26 November 2026

Practice API Design-first in Apidog

Discover an easier way to build and use APIs

How to Verify an API Rewrite With Differential Testing