Contract Test Validator
Overview
Validate API contracts between services using consumer-driven contract testing to prevent breaking changes in microservice architectures. Supports Pact (the industry standard for CDC testing), Spring Cloud Contract (JVM), and OpenAPI-diff for specification comparison.
Prerequisites
- Contract testing framework installed (Pact JS/Python/JVM, or Spring Cloud Contract)
- Pact Broker running (or PactFlow SaaS) for contract storage and verification
- Consumer and provider services with clearly defined API boundaries
- Existing integration points documented (which consumers call which provider endpoints)
- CI pipeline configured for both consumer and provider repositories
Instructions
- Identify consumer-provider relationships in the system:
- Map which services call which APIs (e.g., Frontend calls User API, Order API calls Payment API).
- Document each interaction: HTTP method, path, headers, request body, expected response.
- Prioritize contracts for the most critical and frequently changing integrations.
- Write consumer-side contract tests (Pact consumer tests):
- Define the expected interaction: method, path, query parameters, headers, request body.
- Specify the expected response: status code, headers, and response body structure.
- Use matchers for flexible assertions (
like(), eachLike(), term()) instead of exact values.
- Generate a Pact file (JSON contract) from the consumer test.
- Publish consumer contracts to the Pact Broker:
- Run
pact-broker publish with the consumer version and branch/tag.
- Enable webhooks to trigger provider verification when new contracts are published.
- Configure can-i-deploy checks in CI to gate deployments.
- Write provider-side verification tests:
- Configure the Pact verifier to fetch contracts from the Pact Broker.
- Set up provider states (test data scenarios matching consumer expectations).
- Run verification against the actual provider implementation.
- Publish verification results back to the Pact Broker.
- Handle contract evolution:
- Adding new fields: Safe -- consumers using matchers will not break.
- Removing fields: Breaking -- coordinate with all consumers before removal.
- Changing field types: Breaking -- requires consumer updates first.
- Use
can-i-deploy to check compatibility before releasing either side.
- For schema-based validation (non-Pact):
- Compare OpenAPI spec versions using
openapi-diff to detect breaking changes.
- Flag removed endpoints, changed parameter types, and narrowed response schemas.
- Run schema validation tests against the actual API responses.
- Integrate contract tests into the CI/CD pipeline for both consumers and providers.
Output
- Consumer Pact test files defining expected API interactions
- Generated Pact contract files (JSON) in
pacts/ directory
- Provider verification test configuration
- Pact Broker deployment with published contracts and verification status
- CI pipeline integration with
can-i-deploy deployment gates
- Contract evolution report flagging breaking vs. non-breaking changes
Error Handling
| Error |
Cause |
Solution |
| Provider verification fails |
Provider response does not match consumer expectations |
Check if the contract is outdated; update consumer tests if the change is intentional; fix provider if regression |
can-i-deploy blocks release |
Consumer has unverified or failed contracts |
Run provider verification; check if the right version tags are published; verify Pact Broker webhook fired |
| Pact Broker connection error |
Broker URL or credentials misconfigured |
Verify PACT_BROKER_BASE_URL and PACT_BROKER_TOKEN environment variables; check network connectivity |
| Provider state not found |
Consumer test references a state the provider does not implement |
Add the missing provider state setup function; align state names between consumer and provider |
| Too many contracts to maintain |
Every consumer-provider pair has extensive contracts |
Focus on critical interactions; use matchers instead of exact values; consolidate similar interactions |
Examples
Pact consumer test (JavaScript):
import { PactV4 } from '@pact-foundation/pact';
const provider = new PactV4({ consumer: 'Frontend', provider: 'UserAPI' });
describe('User API Contract', () => {
it('fetches a user by ID', async () => {
await provider
.addInteraction()
.given('user with ID 1 exists')
.uponReceiving('a request for user 1')
.withRequest('GET', '/api/users/1', (builder) => {
builder.headers({ Accept: 'application/json' });
})
.willRespondWith(200, (builder) => { # HTTP 200 OK
builder
.headers({ 'Content-Type': 'application/json' })
.jsonBody({
id: like('1'),
name: like('Alice'),
email: like('alice@example.com'),
});
})
.executeTest(async (mockServer) => {
const response = await fetch(`${mockServer.url}/api/users/1`);
const user = await response.json();
expect(user.name).toBeDefined();
});
});
});
Provider verification test:
import { Verifier } from '@pact-foundation/pact';
describe('User API Provider Verification', () => {
it('validates consumer contracts', async () => {
await new Verifier({
providerBaseUrl: 'http://localhost:3000', # 3000: 3 seconds in ms
pactBrokerUrl: process.env.PACT_BROKER_BASE_URL,
pactBrokerToken: process.env.PACT_BROKER_TOKEN,
provider: 'UserAPI',
publishVerificationResult: true,
providerVersion: process.env.GIT_SHA,
stateHandlers: {
'user with ID 1 exists': async () => {
await db.users.create({ id: '1', name: 'Alice', email: 'alice@example.com' });
},
},
}).verifyProvider();
});
});
can-i-deploy CI check:
pact-broker can-i-deploy \
--pacticipant Frontend \
--version $(git rev-parse HEAD) \
--to-environment production \
--broker-base-url $PACT_BROKER_URL \
--broker-token $PACT_BROKER_TOKEN
Resources
1---2name: validating-api-contracts3description: |4 Validate API contracts using consumer-driven contract testing (Pact, Spring Cloud Contract).5 Use when performing specialized testing.6 Trigger with phrases like "validate API contract", "run contract tests", or "check consumer contracts".78allowed-tools: Read, Write, Edit, Grep, Glob, Bash(test:contract-*)9version: 1.0.010author: Jeremy Longshore <jeremy@intentsolutions.io>11license: MIT12compatible-with: claude-code, codex, openclaw13metadata:14 source: https://skillmd.com/skills/micsapp/validating-api-contracts15---1617# Contract Test Validator1819## Overview2021Validate API contracts between services using consumer-driven contract testing to prevent breaking changes in microservice architectures. Supports Pact (the industry standard for CDC testing), Spring Cloud Contract (JVM), and OpenAPI-diff for specification comparison.2223## Prerequisites2425- Contract testing framework installed (Pact JS/Python/JVM, or Spring Cloud Contract)26- Pact Broker running (or PactFlow SaaS) for contract storage and verification27- Consumer and provider services with clearly defined API boundaries28- Existing integration points documented (which consumers call which provider endpoints)29- CI pipeline configured for both consumer and provider repositories3031## Instructions32331. Identify consumer-provider relationships in the system:34 - Map which services call which APIs (e.g., Frontend calls User API, Order API calls Payment API).35 - Document each interaction: HTTP method, path, headers, request body, expected response.36 - Prioritize contracts for the most critical and frequently changing integrations.372. Write consumer-side contract tests (Pact consumer tests):38 - Define the expected interaction: method, path, query parameters, headers, request body.39 - Specify the expected response: status code, headers, and response body structure.40 - Use matchers for flexible assertions (`like()`, `eachLike()`, `term()`) instead of exact values.41 - Generate a Pact file (JSON contract) from the consumer test.423. Publish consumer contracts to the Pact Broker:43 - Run `pact-broker publish` with the consumer version and branch/tag.44 - Enable webhooks to trigger provider verification when new contracts are published.45 - Configure can-i-deploy checks in CI to gate deployments.464. Write provider-side verification tests:47 - Configure the Pact verifier to fetch contracts from the Pact Broker.48 - Set up provider states (test data scenarios matching consumer expectations).49 - Run verification against the actual provider implementation.50 - Publish verification results back to the Pact Broker.515. Handle contract evolution:52 - Adding new fields: Safe -- consumers using matchers will not break.53 - Removing fields: Breaking -- coordinate with all consumers before removal.54 - Changing field types: Breaking -- requires consumer updates first.55 - Use `can-i-deploy` to check compatibility before releasing either side.566. For schema-based validation (non-Pact):57 - Compare OpenAPI spec versions using `openapi-diff` to detect breaking changes.58 - Flag removed endpoints, changed parameter types, and narrowed response schemas.59 - Run schema validation tests against the actual API responses.607. Integrate contract tests into the CI/CD pipeline for both consumers and providers.6162## Output6364- Consumer Pact test files defining expected API interactions65- Generated Pact contract files (JSON) in `pacts/` directory66- Provider verification test configuration67- Pact Broker deployment with published contracts and verification status68- CI pipeline integration with `can-i-deploy` deployment gates69- Contract evolution report flagging breaking vs. non-breaking changes7071## Error Handling7273| Error | Cause | Solution |74|-------|-------|---------|75| Provider verification fails | Provider response does not match consumer expectations | Check if the contract is outdated; update consumer tests if the change is intentional; fix provider if regression |76| `can-i-deploy` blocks release | Consumer has unverified or failed contracts | Run provider verification; check if the right version tags are published; verify Pact Broker webhook fired |77| Pact Broker connection error | Broker URL or credentials misconfigured | Verify `PACT_BROKER_BASE_URL` and `PACT_BROKER_TOKEN` environment variables; check network connectivity |78| Provider state not found | Consumer test references a state the provider does not implement | Add the missing provider state setup function; align state names between consumer and provider |79| Too many contracts to maintain | Every consumer-provider pair has extensive contracts | Focus on critical interactions; use matchers instead of exact values; consolidate similar interactions |8081## Examples8283**Pact consumer test (JavaScript):**84```typescript85import { PactV4 } from '@pact-foundation/pact';8687const provider = new PactV4({ consumer: 'Frontend', provider: 'UserAPI' });8889describe('User API Contract', () => {90 it('fetches a user by ID', async () => {91 await provider92 .addInteraction()93 .given('user with ID 1 exists')94 .uponReceiving('a request for user 1')95 .withRequest('GET', '/api/users/1', (builder) => {96 builder.headers({ Accept: 'application/json' });97 })98 .willRespondWith(200, (builder) => { # HTTP 200 OK99 builder100 .headers({ 'Content-Type': 'application/json' })101 .jsonBody({102 id: like('1'),103 name: like('Alice'),104 email: like('alice@example.com'),105 });106 })107 .executeTest(async (mockServer) => {108 const response = await fetch(`${mockServer.url}/api/users/1`);109 const user = await response.json();110 expect(user.name).toBeDefined();111 });112 });113});114```115116**Provider verification test:**117```typescript118import { Verifier } from '@pact-foundation/pact';119120describe('User API Provider Verification', () => {121 it('validates consumer contracts', async () => {122 await new Verifier({123 providerBaseUrl: 'http://localhost:3000', # 3000: 3 seconds in ms124 pactBrokerUrl: process.env.PACT_BROKER_BASE_URL,125 pactBrokerToken: process.env.PACT_BROKER_TOKEN,126 provider: 'UserAPI',127 publishVerificationResult: true,128 providerVersion: process.env.GIT_SHA,129 stateHandlers: {130 'user with ID 1 exists': async () => {131 await db.users.create({ id: '1', name: 'Alice', email: 'alice@example.com' });132 },133 },134 }).verifyProvider();135 });136});137```138139**can-i-deploy CI check:**140```bash141pact-broker can-i-deploy \142 --pacticipant Frontend \143 --version $(git rev-parse HEAD) \144 --to-environment production \145 --broker-base-url $PACT_BROKER_URL \146 --broker-token $PACT_BROKER_TOKEN147```148149## Resources150151- Pact documentation: https://docs.pact.io/152- PactFlow (managed Pact Broker): https://pactflow.io/153- Spring Cloud Contract: https://spring.io/projects/spring-cloud-contract154- openapi-diff: https://github.com/OpenAPITools/openapi-diff155- Consumer-Driven Contracts: https://martinfowler.com/articles/consumerDrivenContracts.html