StackPractices
advanced By Mathias Paulenko

Contract Testing: Verify Consumer-Producer API Contracts

How to use contract testing to verify that API producers and consumers agree on request and response shapes. Covers Pact consumer-driven contracts and provider verification.

Topics: testing

Overview

Contract testing verifies that two communicating services agree on the shape of the requests and responses they exchange. In a microservice architecture a single provider API can end up serving dozens of consumers, and each one depends on its own set of fields. The traditional answer, spinning everything up and running integration tests, doesn’t scale: the environments are expensive, the tests are slow, and they fail for a hundred reasons unrelated to the actual integration.

Contract testing flips the direction. Each consumer writes a contract describing exactly what it needs from the provider, and the provider verifies it can satisfy every published contract. If the provider renames a field, its own test suite fails before the change reaches production, no shared environment required. Pact popularized this consumer-driven model and remains the de facto standard; Spring Cloud Contract covers the JVM world.

flowchart diagram: C([Consumer test

When to Use

  • Microservice architectures where services talk over HTTP or message queues
  • Consumers and providers owned by different teams, where a breaking change in one repo breaks another team’s deploy
  • As a replacement for slow, brittle end-to-end integration tests that mostly fail on environment issues
  • Deploy pipelines where you need an automated answer to “is this version safe to ship?”
  • Any time you need confidence that services integrate without deploying them together

When NOT to Use

  • Monoliths, where internal function calls don’t need contracts
  • Single-team codebases where consumer and provider ship together and integration tests are cheap
  • APIs that are stable and rarely change; the broker and contract maintenance aren’t free
  • Business logic testing: contracts verify shape and semantics of the interface, not correctness of what the provider computes
  • Full end-to-end verification: contracts complement a thin E2E layer, they don’t replace it

Solution

The pieces: the consumer records its expectations against a Pact mock server, which produces a pact file; the provider replays that file against its real implementation. A broker in the middle shares contracts across teams, and can-i-deploy turns the whole thing into a release gate.

Consumer-driven contract with Pact (JavaScript)

The consumer test defines each interaction (request in, expected response out) and Pact writes the contract file when the suite passes:

// JavaScript — Consumer: write the contract
const { Pact } = require('@pact-foundation/pact');
const path = require('path');

const provider = new Pact({
  consumer: 'order-service',
  provider: 'user-service',
  port: 8080,
  log: path.resolve(__dirname, 'logs', 'pact.log'),
  dir: path.resolve(__dirname, 'pacts'),
});

describe('User Service Contract', () => {
  beforeAll(() => provider.setup());
  afterAll(() => provider.finalize());
  afterEach(() => provider.verify());

  test('GET /users/:id returns user', async () => {
    // Define the expected interaction
    await provider.addInteraction({
      uponReceiving: 'a request for a user',
      withRequest: {
        method: 'GET',
        path: '/users/1',
        headers: { Accept: 'application/json' },
      },
      willRespondWith: {
        status: 200,
        headers: { 'Content-Type': 'application/json' },
        body: {
          id: 1,
          name: 'Alice',
          email: 'alice@x.com',
          role: 'admin',
        },
      },
    });

    // Call the provider (using the mock URL)
    const user = await getUser(1);

    expect(user).toEqual({
      id: 1,
      name: 'Alice',
      email: 'alice@x.com',
      role: 'admin',
    });
  });

  test('POST /users creates a new user', async () => {
    await provider.addInteraction({
      uponReceiving: 'a request to create a user',
      withRequest: {
        method: 'POST',
        path: '/users',
        headers: { 'Content-Type': 'application/json' },
        body: { name: 'Bob', email: 'bob@x.com' },
      },
      willRespondWith: {
        status: 201,
        headers: { 'Content-Type': 'application/json' },
        body: {
          id: 2,
          name: 'Bob',
          email: 'bob@x.com',
          role: 'member',
        },
      },
    });

    const user = await createUser({ name: 'Bob', email: 'bob@x.com' });

    expect(user.id).toBe(2);
    expect(user.name).toBe('Bob');
  });
});

Provider verification (JavaScript)

On the provider side the flow inverts: run the real API, point the Verifier at the pact files (or the broker), and it replays every recorded interaction:

// JavaScript — Provider: verify the contract
const { Verifier } = require('@pact-foundation/pact');

describe('Pact Verification', () => {
  test('verifies pacts from the broker', async () => {
    const opts = {
      providerBaseUrl: 'http://localhost:3000',
      pactUrls: [
        path.resolve(__dirname, 'pacts', 'order-service-user-service.json'),
      ],
      // Or fetch from Pact Broker:
      // pactBrokerUrl: 'https://broker.example.com',
      // consumerVersionTags: ['main'],
      providerVersion: '1.0.0',
      provider: 'user-service',
    };

    await new Verifier(opts).verifyProvider();
  });
});

Consumer contract with Pact (Python)

The same model in pact-python: identical concepts, pytest-friendly API:

# Python — Consumer: write the contract with pact-python
import pytest
from pact import Consumer, Provider

pact = Consumer('order-service').has_pact_with(
    Provider('user-service'),
    pact_dir='pacts/',
    host_name='localhost',
    host_port=8080,
)

@pytest.fixture
def user_client():
    return UserClient(base_url='http://localhost:8080')

def test_get_user_contract(user_client):
    # Define expected interaction
    (
        pact
        .given('a user with id 1 exists')
        .upon_receiving('a request for user 1')
        .with_request('GET', '/users/1', headers={'Accept': 'application/json'})
        .will_respond_with(200, body={
            'id': 1,
            'name': 'Alice',
            'email': 'alice@x.com',
            'role': 'admin',
        })
    )

    with pact:
        user = user_client.get_user(1)

    assert user['name'] == 'Alice'
    assert user['email'] == 'alice@x.com'

def test_create_user_contract(user_client):
    (
        pact
        .given('no user with email bob@x.com exists')
        .upon_receiving('a request to create a user')
        .with_request(
            'POST',
            '/users',
            headers={'Content-Type': 'application/json'},
            body={'name': 'Bob', 'email': 'bob@x.com'},
        )
        .will_respond_with(201, body={
            'id': 2,
            'name': 'Bob',
            'email': 'bob@x.com',
            'role': 'member',
        })
    )

    with pact:
        user = user_client.create_user(name='Bob', email='bob@x.com')

    assert user['id'] == 2
    assert user['name'] == 'Bob'

Provider verification (Python)

# Python — Provider: verify the contract
import pytest
from pact.verifier import Verifier

class TestProviderVerification:
    def test_verify_pacts(self):
        verifier = Verifier(
            provider='user-service',
            provider_base_url='http://localhost:5000',
        )

        result = verifier.verify_pacts(
            'pacts/order-service-user-service.json',
            # Or from broker:
            # broker_url='https://broker.example.com',
            # consumer_version_tags=['main'],
            provider_version='1.0.0',
        )

        assert result == 0  # 0 = all pacts verified

Pact with matchers (flexible contracts)

Exact values make brittle contracts. If the provider returns "Alice" today and "Bob" tomorrow, the exact match fails even though the API didn’t actually change. Matchers fix that by asserting on types and shapes instead of literals:

// JavaScript — use matchers instead of exact values
const { like, eachLike, term, regex } = require('@pact-foundation/pact').MatchersV3;

test('GET /users returns a list', async () => {
  await provider.addInteraction({
    uponReceiving: 'a request for all users',
    withRequest: {
      method: 'GET',
      path: '/users',
      query: { page: '1', per_page: '20' },
    },
    willRespondWith: {
      status: 200,
      body: {
        data: eachLike({
          id: like(1),
          name: like('Alice'),
          email: like('alice@x.com'),
          role: term({
            generate: 'member',
            matcher: 'admin|member|guest',
          }),
        }),
        pagination: {
          page: like(1),
          per_page: like(20),
          total: like(100),
        },
      },
    },
  });

  const response = await getUsers({ page: 1, perPage: 20 });

  expect(response.data).toHaveLength(1);
  expect(response.data[0].name).toBe('Alice');
});

like() asserts type, eachLike() asserts every element of a list, and term() checks a regex. A name that’s any string satisfies the contract; a missing field breaks it, which is the distinction you actually care about.

Pact with states (provider states)

Some interactions only make sense given preconditions like “a user with id 1 exists.” Provider states declare them in the contract, and the provider exposes a setup endpoint that creates the data before each replay:

// JavaScript — provider states for setup
// Consumer side
await provider.addInteraction({
  state: 'a user with id 1 exists',
  uponReceiving: 'a request for user 1',
  withRequest: { method: 'GET', path: '/users/1' },
  willRespondWith: {
    status: 200,
    body: { id: 1, name: 'Alice' },
  },
});

// Provider side — handle state setup
app.post('/pact-state-setup', (req, res) => {
  const { state } = req.body;

  switch (state) {
    case 'a user with id 1 exists':
      testDb.insert({ id: 1, name: 'Alice', email: 'alice@x.com' });
      break;
    case 'no users exist':
      testDb.truncate('users');
      break;
    default:
      res.status(400).json({ error: `Unknown state: ${state}` });
      return;
  }

  res.status(200).json({ setup: state });
});

Without states, a “user not found” or “order already shipped” contract is impossible to verify: the provider has no way to put itself into the condition the consumer described.

Pact Broker integration

The broker is what turns local contracts into a cross-team system: consumers publish their pact files tagged with the commit SHA, providers verify against them and publish the result back. For a runnable CI version of this pattern, see the contract testing recipe:

# .github/workflows/contract-tests.yml
name: Contract Tests

on: [push, pull_request]

jobs:
  consumer-test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm
      - run: npm ci
      - name: Run consumer tests
        run: npx jest --testPathPattern=contract
      - name: Publish pacts to broker
        run: |
          npx pact-broker publish pacts/ \
            --consumer-app-version ${{ github.sha }} \
            --broker-base-url ${{ secrets.PACT_BROKER_URL }} \
            --broker-token ${{ secrets.PACT_BROKER_TOKEN }}
        env:
          PACT_BROKER_URL: ${{ secrets.PACT_BROKER_URL }}

  provider-verify:
    needs: consumer-test
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:16
        env:
          POSTGRES_PASSWORD: test
        ports:
          - 5432:5432
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm
      - run: npm ci
      - name: Start provider
        run: |
          npm run start &
          sleep 5
      - name: Verify pacts from broker
        run: |
          npx pact-broker verify \
            --broker-base-url ${{ secrets.PACT_BROKER_URL }} \
            --broker-token ${{ secrets.PACT_BROKER_TOKEN }} \
            --provider-base-url http://localhost:3000 \
            --provider user-service \
            --provider-app-version ${{ github.sha }}

Message queue contract testing

Contracts work for async too: the consumer records the message shape it expects to receive, and the provider (the event producer) verifies it publishes messages in that shape:

# Python — contract testing for message queues
from pact import Consumer, Provider

pact = Consumer('notification-service').has_pact_with(
    Provider('order-service'),
    pact_dir='pacts/',
)

def test_order_created_message_contract():
    (
        pact
        .given('an order is created')
        .expects_to_receive('an order created event')
        .with_content({
            'event_type': 'order.created',
            'order_id': 123,
            'customer_email': 'alice@x.com',
            'total': 99.99,
        })
    )

    with pact:
        # Consumer processes the message
        message = pact.consume_message('order-events')
        notification = process_order_created(message)

    assert notification.recipient == 'alice@x.com'
    assert 'order' in notification.subject.lower()

Explanation

The lifecycle has four stages, and each one has a failure mode worth understanding. First, the consumer test runs against Pact’s local mock server. The mock answers with whatever willRespondWith declared, so the consumer never touches the real provider. When the suite passes, Pact writes a JSON pact file per consumer-provider pair.

Second, the contract travels. Committed pact files work for a single repo, but the real value is a Pact Broker: the consumer’s CI publishes the file tagged with its commit SHA, which is what makes the contract traceable to a deployable version.

Third, the provider’s CI pulls the contract and replays every interaction against the real API. That’s the moment provider states run: the replay lands on data in the exact condition the consumer described. Verification results get reported back to the broker, so the record stays current.

Fourth, can-i-deploy asks the broker the only question that matters: “is this version of order-service compatible with every contract it’s involved in?” If any consumer pact is unsatisfied, the deploy stops. This is the gate that catches the classic production incident: the provider renames email to email_address, everything passes unit tests, three consumers break at once.

What contracts do not verify: that the provider’s answers are correct, that the data makes sense, that auth works, or that the system behaves end to end. A contract is an interface assertion, not a system test. It sits above unit tests and below the thin E2E layer in the test pyramid, where it replaces the fat middle of integration suites.

A few things teams learn the hard way: contracts multiply fast (each consumer-provider pair is one file, and thirty consumers means thirty verifications per provider deploy), provider states are where test realism lives or dies, and a broker is nearly mandatory once more than two services participate. Passing JSON files around by hand breaks down almost immediately.

Variants

Bi-directional contract testing

Pactflow’s bi-directional mode compares the provider’s OpenAPI spec against consumer contracts, useful when the spec already exists and you want consumer coverage without writing provider states:

# OpenAPI spec as provider contract + Pact as consumer contract
# Use Pactflow bi-directional feature to compare

# Provider: generate OpenAPI spec
openapi: 3.0.0
info:
  title: User Service API
  version: 1.0.0
paths:
  /users/{id}:
    get:
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
      responses:
        '200':
          description: User found
          content:
            application/json:
              schema:
                type: object
                properties:
                  id:
                    type: integer
                  name:
                    type: string
                  email:
                    type: string

Contract testing with Spring Cloud Contract

The JVM ecosystem’s take: contracts are Groovy/YAML definitions that live with the provider, which auto-generates both verification tests for itself and stubs consumers can test against:

// Java — Spring Cloud Contract DSL
// src/test/resources/contracts/user_service/get_user_by_id.groovy
Contract.make {
    request {
        method 'GET'
        url '/users/1'
        headers {
            accept(applicationJson())
        }
    }
    response {
        status 200
        headers {
            contentType(applicationJson())
        }
        body([
            id: 1,
            name: 'Alice',
            email: 'alice@x.com',
            role: 'admin',
        ])
    }
}

// Provider test auto-generated by Spring Cloud Contract
@AutoConfigureStubRunner
class UserContractTest {

    @Test
    void validate_user_contract() throws Exception {
        // Auto-generated test from the contract
        mockMvc.perform(get("/users/1")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.name").value("Alice"))
                .andExpect(jsonPath("$.email").value("alice@x.com"));
    }
}

Can-I-Deploy check

The broker’s release gate. Run it in the deploy pipeline before shipping a participant version:

# Check if it's safe to deploy — verifies all contracts are satisfied
npx pact-broker can-i-deploy \
  --broker-base-url $PACT_BROKER_URL \
  --broker-token $PACT_BROKER_TOKEN \
  --participant order-service \
  --version $GIT_SHA \
  --to-environment production

# Exit 0: safe to deploy
# Exit 1: not safe — a contract is broken

What Works

  • Consumer-driven, always. The consumer declares what it needs; the provider verifies it can deliver it. Provider-authored contracts drift toward “what we happen to return” and stop catching real breakage.
  • Matchers over literals. like(), term(), eachLike() assert on shape. Exact values turn each contract into a snapshot test that fails on data noise.
  • One interaction per contract. Small, focused interactions tell you exactly what broke when verification fails.
  • Provider states for preconditions. Any expectation about existing data needs a state; without one, the provider can’t set the stage for the replay.
  • Publish to a broker from day one. Local pact files don’t scale past two services. The broker is what makes cross-team verification and can-i-deploy possible.
  • Both sides in CI. Consumer tests publish contracts; provider verification replays them. Running only one side gives you a filing cabinet nobody reads.
  • Tag contracts with the commit SHA. Traceability to a deployable version is what makes can-i-deploy meaningful.
  • Keep a thin E2E layer anyway. Contracts verify the interface, not the system. For the fixture lifecycle side of that E2E layer, see Fixture Setup/Teardown Pattern.

Common Mistakes

  • Exact value matching. "Alice" in a contract breaks the moment the provider returns "Bob", same shape, different data. Reach for like() on anything that isn’t structurally required.
  • Skipping provider states. Without them, contracts like “user not found” or “order already shipped” can’t be verified at all, because the provider has no way to reach that condition.
  • No broker. Passing pact files around by hand works until the second team joins. Then contracts go stale and verification quietly stops happening.
  • Testing business logic in contracts. A contract that asserts total == price * qty tests the provider’s math, not the interface, and fails when the math legitimately changes. Assert shape, types, and required fields.
  • Consumer-only contracts. Consumers write contracts that providers never verify, and a contract nobody replays is just a wish list. Both halves have to run in CI, or the loop never closes.

See Also

Frequently Asked Questions

What is consumer-driven contract testing?

The consumer writes a contract describing the interactions it depends on: which endpoints, which fields, which shapes. The provider then replays each contract against its real implementation and fails the build when it can't satisfy one. The direction matters: the provider learns what consumers actually use, instead of guessing which parts of its API are load-bearing.

What is a Pact Broker?

It's a service that stores the pact files and tracks which version of each participant satisfies which contract. It's what makes can-i-deploy checks, cross-team verification, and contract versioning by commit SHA possible. Pactflow is the hosted version; the open-source broker runs as a Docker container.

How is contract testing different from integration testing?

Integration tests deploy real services together and exercise the full stack, which is slow, expensive, and they fail on environment problems as often as real bugs. Contract tests verify the interface without deploying together: the consumer tests against a mock, the provider replays recorded interactions. You keep a thin E2E layer for what contracts can't see, but the bulk of interface coverage moves to contracts.

What are provider states?

Preconditions the provider must satisfy before a replayed interaction, like "a user with id 1 exists" or "the order is already shipped." The provider exposes a setup endpoint that creates the data for each named state. Without them there's no way to verify a contract that assumes existing data.

Should I use contract testing or OpenAPI validation?

Both, for different jobs. OpenAPI validation only checks the provider's implementation against its own spec. It catches spec drift but knows nothing about consumers. Contract testing checks the provider against what its consumers actually depend on. An endpoint can be spec-perfect and still break every consumer that expected a field the spec deprecated quietly.