FDE Times dataFDE jobs open 932▼14 Change in open roles over 7 days, like-for-like: roles from companies we started tracking this week are left outNew in 7 days 62Companies hiring 202Remote-friendly 24%Median US pay $201kTop hirer Databricks 92
中文VI

The newspaper of the Forward Deployed Engineer

Guides

One renamed field can quietly zero out your revenue report

An afternoon with a mock server and contract tests in plain Python is enough to catch a client's API change before the numbers go wrong.

ShareLinkedInFacebookX

In brief

  • A mock lets you write and test code before the client's API is ready, but it will not tell you when the client changes that API.
  • A contract test relies on one shared description file: you test your side against the mock, then send each request in the file to the real API to check it.
  • Don't over-mock: critical flows still need to run against the real API, and the contract must be updated whenever the API changes.
Diagram: a contract.json file at the top splits into two branches. Left branch: a mock built from the contract, used to test your code; when the client changes a field, the test stays green. Right branch (highlighted): verify_provider sends the contract to the client's real API; when the client changes a field, the result is FAIL.
One contract.json both generates the mock that lets you start work early and is checked against the real API. Only the verify step catches the moment a client renames a field.

Take an integration with a client’s order system that you deploy on Monday, with every test green. On Thursday, the client’s backend team renames the field total to amount and tells no one. Your code doesn’t crash. It quietly returns None, and the revenue report at the end of the week comes out at 0.

A failure like this doesn’t need a complicated bug. It only needs two teams working on the same integration point with nothing holding them to their agreement. For an FDE the risk is sharper, because the API usually sits on the client’s side: you probably don’t control their release schedule, and you may not be allowed to read their code.

This guide covers two jobs in one afternoon. The first is mocking the client’s API so you can start work right away. The second is writing contract tests so you know as soon as the client changes it.

What you will build

You will build four pieces: a contract file, a mock server, a test for your side and a verify script that runs against the real API. You need Python 3, a terminal and, if possible, the staging URL of a real API to try the last step.

The code below is a hand-rolled, simplified version that uses only Python’s standard library, so you can see the mechanism inside. On a real project, Pact does this work for you.

Pact’s documentation describes it as a “code-first” tool for contract testing both HTTP and message integrations, aimed mainly at developers and testers who write code. For Pact’s exact syntax, see docs.pact.io; here the mechanism is rebuilt by hand to show how it works.

Step 1: Write down the agreement before you write code

Pact works like this: tests on the consumer side (the side calling the API, meaning you) generate a pact file that describes each interaction. Here you write that file by hand, using a hypothetical client orders API:

{
  "consumer": "fde-integration",
  "provider": "customer-orders-api",
  "interactions": [
    {
      "description": "get an existing order",
      "request": {"method": "GET", "path": "/orders/42"},
      "response": {"status": 200,
                   "body": {"id": 42, "status": "PAID", "total": 150000}}
    },
    {
      "description": "order does not exist",
      "request": {"method": "GET", "path": "/orders/999"},
      "response": {"status": 404, "body": {"error": "not_found"}}
    }
  ]
}

Save it as contract.json. Check: give the file to an engineer on the client’s side. If they confirm the API returns exactly this, you have your first written agreement, and any misunderstanding between the two sides surfaces here.

The 404 case is there on purpose. A mock lets you test beyond the usual scenarios, and error cases are where integration code breaks easily and few people test.

Step 2: Build the mock from the contract itself

A mock API is a web service that simulates the real one, and it is useful from the earliest stage, before the real service is ready. This mock reads straight from the contract, so the two never drift apart:

# mock_server.py — simplified, matches on path only
import json
from http.server import BaseHTTPRequestHandler, HTTPServer

CONTRACT = json.load(open("contract.json"))

class Mock(BaseHTTPRequestHandler):
    def do_GET(self):
        for it in CONTRACT["interactions"]:
            if it["request"]["path"] == self.path:
                res = it["response"]
                self.send_response(res["status"])
                self.send_header("Content-Type", "application/json")
                self.end_headers()
                self.wfile.write(json.dumps(res["body"]).encode())
                return
        self.send_response(500)
        self.end_headers()

HTTPServer(("localhost", 8001), Mock).serve_forever()
python3 mock_server.py &
curl -i http://localhost:8001/orders/999

Check: you should see HTTP/1.0 404 and the body {"error": "not_found"}. Calling a path that is not in the contract returns 500. That error is deliberate: your code is calling something the agreement doesn’t cover.

Step 3: Test your code against the mock

Here is the actual integration code, followed by its test:

# client.py
import json, urllib.request, urllib.error

def get_order_total(base_url, order_id):
    try:
        with urllib.request.urlopen(f"{base_url}/orders/{order_id}") as r:
            return json.load(r).get("total")
    except urllib.error.HTTPError as e:
        if e.code == 404:
            return None
        raise
# test_consumer.py
from client import get_order_total
BASE = "http://localhost:8001"
assert get_order_total(BASE, 42) == 150000
assert get_order_total(BASE, 999) is None
print("consumer OK")

Check: python3 test_consumer.py prints consumer OK. Look at .get("total"): when the field disappears, the function raises no error and returns None. This is the silent failure from the opening, and a lot of integration code is written this way.

A mock is an isolated API, unaffected by changes in services, databases or external systems. That is why this test runs even when the client’s staging is down.

The same isolation is also its weakness. If the client renames total to amount, the mock still returns total and the test stays green. The mock helps when the client isn’t ready; it cannot tell you that the client has changed the API.

Step 4: Put the contract to the real API

This is the other half, and the reason the contract exists. Pact calls this step provider verification: each request in the pact is sent to the provider. Contract testing checks an integration point by examining each application in isolation. You test your side against the mock, and the client’s side is tested with the same file.

# verify_provider.py — simplified: compares status and field names, not values
import json, sys, urllib.request, urllib.error

contract = json.load(open("contract.json"))
base = sys.argv[1]
fails = 0
for it in contract["interactions"]:
    req, exp = it["request"], it["response"]
    try:
        r = urllib.request.urlopen(base + req["path"])
        status, body = r.status, json.load(r)
    except urllib.error.HTTPError as e:
        status, body = e.code, json.load(e)
    missing = [k for k in exp["body"] if k not in body]
    if status != exp["status"] or missing:
        fails += 1
        print(f"FAIL {it['description']}: status={status}, missing {missing}")
sys.exit(1 if fails else 0)
python3 verify_provider.py https://staging.customer.example

The script deliberately compares field names and ignores values, because order 42 on the client’s staging certainly won’t total exactly 150000. Check: when the client renames the field, you will see FAIL get an existing order: status=200, missing ['total'] and exit code 1.

Contract tests make debugging much faster, and that line of output shows why: the error names the exact field and the exact interaction, where a dashboard would show only a mysterious 0.

There is a hidden assumption: order 42 must exist on staging. Agree on fixed test data with the client, or the verify step will go red for reasons unrelated to the contract.

Step 5: Put it in CI so nobody has to remember

A script that someone must remember to run will sooner or later be forgotten. Schedule verify_provider.py in CI; because it returns a nonzero exit code on failure, the pipeline turns red by itself.

With Pact, the Pact Broker handles the connection to CI. When the number of APIs and teams that need verifying starts to grow, it is time to drop the hand-rolled version and switch.

Three common mistakes

The first is over-mocking. The principle is to avoid it and use the real API whenever possible, especially for critical flows. If the client’s payment flow has only ever run against a mock, you haven’t really tested it.

The second is letting the contract stand still. Tests reflect the system only if they are updated as the API changes. When the client announces an API change, edit contract.json before you touch the code. The mock and the verify step will follow.

The third is matching too strictly. If you assert every value against real data, the test will go red every day and the whole team will learn to ignore it.

Where this pays off on a client site

In your first week at a client, the API is often unfinished and the documentation out of date. Writing contract.json and taking it to the client’s engineers is the fastest way to expose what the two sides understand differently, before anyone writes a line of code.

Once the system is in operation, a nightly verify run tells you the client has just changed the API, so you don’t have to wait for their phone call.

On your CV, go further than “knows Pact.” State how many interactions you built contracts for and what kind of change you stopped before it reached production.

Your integration code works correctly only as long as the client’s API stays as the two sides agreed. A contract test is how you check that every day.

Was this article useful?

Use with your AI assistantAsk Claude ↗Ask ChatGPT ↗
6 sources
Read next on the roadmap · Stage 5: DeploymentYour model is accurate. Who accepted the risk that remains?European clients' AI boards want residual risk named and signed for under Article 9 of the EU AI Act, in a file that lives with the system.