Purpose & When-To-Use
Trigger conditions:
- Microservices communicating via REST/GraphQL APIs requiring contract guarantees
- Mobile or web frontend consuming backend APIs with version safety requirements
- API provider needing to verify backward compatibility before deployment
- CI/CD pipeline requiring automated contract verification gates
- Team transitioning from manual integration tests to consumer-driven contracts
- Schema evolution requiring breaking change detection
Use this skill when you need to establish or validate API contracts between consumers and providers, detect schema drift, prevent breaking changes, and integrate contract testing into CI/CD pipelines.
Pre-Checks
Before execution, verify:
- Time normalization:
NOW_ET = 2025-10-26T06:31:34-04:00 (NIST/time.gov semantics, America/New_York)
- Input schema validation:
api_spec is valid OpenAPI 3.x JSON/YAML, service description, or contract DSL
role is exactly "consumer" or "provider"
framework is exactly "pact", "spring-contract", or "openapi"
language (if provided) is supported by chosen framework
- Source freshness: All cited sources accessed on
NOW_ET; verify links resolve
- Framework availability: Confirm framework tooling available for target language
Abort conditions:
api_spec is invalid JSON/YAML or missing required fields (paths, operations)
framework and language combination not supported (e.g., Pact with COBOL)
- No clear consumer-provider relationship identifiable from spec
- Circular contract dependencies detected
Procedure
T1: Basic Contract Test Generation (≤2k tokens)
Scope: Generate minimal consumer or provider contract test for single endpoint.
Steps:
- Parse
api_spec: Extract endpoint path, method, request/response schema
- Select template: Choose framework-specific test template (Pact DSL, Spring Contract DSL, or OpenAPI validator)
- Generate test code:
- Consumer (Pact): Mock provider, define interaction, verify request/response
- Provider (Pact): Verify against published consumer contracts
- OpenAPI: Generate request/response validation using OpenAPI schema
- Output: Minimal runnable test file with single interaction
Example output: Pact consumer test for GET /users/:id endpoint (JavaScript).
T2: Multi-Endpoint Verification with CI Integration (≤6k tokens)
Scope: Generate comprehensive contract tests for 3-5 endpoints with CI pipeline integration.
Steps:
- Endpoint analysis: Identify all consumer-provider interactions from
api_spec
- Generate test suite:
- Consumer: Full test suite covering happy path, edge cases, error responses
- Provider: Verification tests against all published consumer contracts
- Breaking change detection:
- Compare new
api_spec against existing contract (if available)
- Flag removed endpoints, changed response schemas, new required fields
- CI integration:
- Generate pipeline YAML (GitHub Actions, GitLab CI, Jenkins)
- Include contract publish/verify steps, Pact Broker integration
- Add gates for breaking change detection
- Output: Test suite + CI config + compatibility report
Sources (accessed 2025-10-26T06:31:34-04:00):
T3: Schema Evolution and Advanced Validation (≤12k tokens)
Scope: Deep analysis of schema evolution, versioning strategies, and contract governance.
Steps:
- Historical contract analysis: Load previous contract versions, compute diff
- Breaking change taxonomy:
- Critical: Removed endpoints, deleted required fields, type changes
- Warning: New required fields without defaults, renamed fields
- Safe: New optional fields, added endpoints, relaxed constraints
- Versioning strategy:
- Recommend approach: URL versioning, header versioning, or content negotiation
- Generate migration path for breaking changes
- Contract governance:
- Define approval workflow (provider must verify consumer contracts before deploy)
- Set up Pact Broker webhooks for contract change notifications
- Generate compatibility matrix (which consumer versions work with which provider versions)
- Advanced testing scenarios:
- State-based testing (Pact provider states)
- Message queue contracts (Pact for async messaging)
- GraphQL schema stitching contracts
- Output: Comprehensive report + versioning plan + governance workflow + advanced test examples
Additional sources (accessed 2025-10-26T06:31:34-04:00):
Decision Rules
Framework selection:
- Use Pact when: Consumer-driven workflow, polyglot environment, Pact Broker available
- Use Spring Cloud Contract when: Spring Boot ecosystem, provider-driven workflow preferred
- Use OpenAPI validation when: Spec-first design, simple request/response validation sufficient
Test generation depth:
- T1 only when: Single endpoint, proof-of-concept, immediate feedback needed
- T2 when: Production system, CI integration required, 3-10 endpoints
- T3 when: Complex versioning, multiple consumers, governance required, >10 endpoints
Breaking change severity:
- Block deployment if: Removed endpoints used by active consumers, required field deleted
- Warn but allow if: New optional field, added endpoint, relaxed validation
- Auto-approve if: Only documentation changes, no schema modifications
Ambiguity thresholds:
- If
api_spec has >20 endpoints, request focus on specific consumer-provider pair
- If breaking changes detected but no previous contract available, emit warning and proceed
- If circular dependencies detected (A depends on B, B depends on A), emit error and abort
Output Contract
Required fields (all tiers):
{
"contract_tests": {
"type": "code",
"language": "javascript|java|python|go",
"framework": "pact|spring-contract|openapi",
"file_path": "path/to/test/file",
"content": "// Full test code..."
},
"contract_spec": {
"type": "json|yaml",
"format": "pact_v3|spring_contract_dsl|openapi_3.1",
"content": "{ ... contract JSON ... }"
}
}
T2+ additional fields:
{
"ci_integration": {
"type": "yaml",
"pipeline": "github_actions|gitlab_ci|jenkins",
"content": "# Pipeline config..."
},
"validation_report": {
"type": "markdown",
"breaking_changes": [
{
"severity": "critical|warning|safe",
"description": "Removed endpoint /users/:id",
"affected_consumers": ["mobile-app", "web-ui"]
}
],
"compatibility_matrix": "table of consumer/provider version compatibility"
}
}
T3 additional fields:
{
"versioning_plan": {
"type": "markdown",
"strategy": "url|header|content_negotiation",
"migration_steps": ["step 1", "step 2"]
},
"governance_workflow": {
"type": "markdown",
"approval_process": "description",
"pact_broker_config": "webhook and notification setup"
}
}
Examples
Example 1: Pact Consumer Test (JavaScript, ≤30 lines)
const { PactV3, MatchersV3 } = require('@pact-foundation/pact');
const { getUserById } = require('./api-client');
const provider = new PactV3({ consumer: 'mobile-app', provider: 'user-service' });
describe('User API Contract', () => {
it('gets user by ID', () => {
provider
.given('user 123 exists')
.uponReceiving('a request for user 123')
.withRequest({
method: 'GET',
path: '/users/123',
headers: { Accept: 'application/json' },
})
.willRespondWith({
status: 200,
headers: { 'Content-Type': 'application/json' },
body: {
id: MatchersV3.like(123),
name: MatchersV3.like('Alice'),
email: MatchersV3.email('alice@example.com'),
},
});
return provider.executeTest(async (mockServer) => {
const user = await getUserById(mockServer.url, 123);
expect(user.name).toBe('Alice');
});
});
});
See /skills/api-contract-testing/resources/ for Spring Cloud Contract and OpenAPI examples.
Quality Gates
Token budgets (strict):
- T1: ≤2000 tokens (single endpoint test generation)
- T2: ≤6000 tokens (multi-endpoint + CI + breaking change detection)
- T3: ≤12000 tokens (schema evolution + governance + versioning)
Safety requirements:
- All generated tests must be runnable or marked as pseudo-code
- No hardcoded secrets or production API keys in test code
- All URLs in contract specs must be localhost or mock servers
Auditability:
- All breaking changes must be logged with severity and affected consumers
- Contract evolution history must be traceable via Pact Broker or version control
- CI integration must include contract verification as blocking gate
Determinism:
- Same
api_spec + role + framework must generate identical contract tests
- Breaking change detection must be idempotent (same input = same output)
Validation:
- Generated Pact JSON must validate against Pact JSON Schema v3
- OpenAPI contracts must validate against OpenAPI 3.1 spec
- Spring Contract DSL must compile without errors
Resources
Official Documentation (accessed 2025-10-26T06:31:34-04:00):
Tools and Libraries:
Best Practices:
Example Repositories:
1---2name: api-contract-testing-validator3description: Generate and validate API contract tests using Pact, Spring Cloud Contract, or OpenAPI with consumer-driven contracts and schema drift detection.4license: MIT5---67## Purpose & When-To-Use89**Trigger conditions:**1011- Microservices communicating via REST/GraphQL APIs requiring contract guarantees12- Mobile or web frontend consuming backend APIs with version safety requirements13- API provider needing to verify backward compatibility before deployment14- CI/CD pipeline requiring automated contract verification gates15- Team transitioning from manual integration tests to consumer-driven contracts16- Schema evolution requiring breaking change detection1718**Use this skill when** you need to establish or validate API contracts between consumers and providers, detect schema drift, prevent breaking changes, and integrate contract testing into CI/CD pipelines.1920---2122## Pre-Checks2324**Before execution, verify:**25261. **Time normalization**: `NOW_ET = 2025-10-26T06:31:34-04:00` (NIST/time.gov semantics, America/New_York)272. **Input schema validation**:28 - `api_spec` is valid OpenAPI 3.x JSON/YAML, service description, or contract DSL29 - `role` is exactly "consumer" or "provider"30 - `framework` is exactly "pact", "spring-contract", or "openapi"31 - `language` (if provided) is supported by chosen framework323. **Source freshness**: All cited sources accessed on `NOW_ET`; verify links resolve334. **Framework availability**: Confirm framework tooling available for target language3435**Abort conditions:**3637- `api_spec` is invalid JSON/YAML or missing required fields (paths, operations)38- `framework` and `language` combination not supported (e.g., Pact with COBOL)39- No clear consumer-provider relationship identifiable from spec40- Circular contract dependencies detected4142---4344## Procedure4546### T1: Basic Contract Test Generation (≤2k tokens)4748**Scope**: Generate minimal consumer or provider contract test for single endpoint.4950**Steps**:51521. **Parse `api_spec`**: Extract endpoint path, method, request/response schema532. **Select template**: Choose framework-specific test template (Pact DSL, Spring Contract DSL, or OpenAPI validator)543. **Generate test code**:55 - **Consumer (Pact)**: Mock provider, define interaction, verify request/response56 - **Provider (Pact)**: Verify against published consumer contracts57 - **OpenAPI**: Generate request/response validation using OpenAPI schema584. **Output**: Minimal runnable test file with single interaction5960**Example output**: Pact consumer test for GET /users/:id endpoint (JavaScript).6162---6364### T2: Multi-Endpoint Verification with CI Integration (≤6k tokens)6566**Scope**: Generate comprehensive contract tests for 3-5 endpoints with CI pipeline integration.6768**Steps**:69701. **Endpoint analysis**: Identify all consumer-provider interactions from `api_spec`712. **Generate test suite**:72 - **Consumer**: Full test suite covering happy path, edge cases, error responses73 - **Provider**: Verification tests against all published consumer contracts743. **Breaking change detection**:75 - Compare new `api_spec` against existing contract (if available)76 - Flag removed endpoints, changed response schemas, new required fields774. **CI integration**:78 - Generate pipeline YAML (GitHub Actions, GitLab CI, Jenkins)79 - Include contract publish/verify steps, Pact Broker integration80 - Add gates for breaking change detection815. **Output**: Test suite + CI config + compatibility report8283**Sources** (accessed 2025-10-26T06:31:34-04:00):8485- Pact documentation: [Consumer-Driven Contracts](https://docs.pact.io/getting_started/what_is_pact)86- Spring Cloud Contract: [Contract DSL Reference](https://spring.io/projects/spring-cloud-contract#overview)87- OpenAPI Specification: [Schema Object](https://spec.openapis.org/oas/v3.1.0#schema-object)88- Pact Broker: [Sharing Pacts](https://docs.pact.io/pact_broker)8990---9192### T3: Schema Evolution and Advanced Validation (≤12k tokens)9394**Scope**: Deep analysis of schema evolution, versioning strategies, and contract governance.9596**Steps**:97981. **Historical contract analysis**: Load previous contract versions, compute diff992. **Breaking change taxonomy**:100 - **Critical**: Removed endpoints, deleted required fields, type changes101 - **Warning**: New required fields without defaults, renamed fields102 - **Safe**: New optional fields, added endpoints, relaxed constraints1033. **Versioning strategy**:104 - Recommend approach: URL versioning, header versioning, or content negotiation105 - Generate migration path for breaking changes1064. **Contract governance**:107 - Define approval workflow (provider must verify consumer contracts before deploy)108 - Set up Pact Broker webhooks for contract change notifications109 - Generate compatibility matrix (which consumer versions work with which provider versions)1105. **Advanced testing scenarios**:111 - State-based testing (Pact provider states)112 - Message queue contracts (Pact for async messaging)113 - GraphQL schema stitching contracts1146. **Output**: Comprehensive report + versioning plan + governance workflow + advanced test examples115116**Additional sources** (accessed 2025-10-26T06:31:34-04:00):117118- Pact versioning: [Versioning with Pact](https://docs.pact.io/getting_started/versioning_in_the_pact_broker)119- API evolution best practices: [Zalando API Guidelines - Compatibility](https://opensource.zalando.com/restful-api-guidelines/#deprecation)120121---122123## Decision Rules124125**Framework selection**:126127- **Use Pact** when: Consumer-driven workflow, polyglot environment, Pact Broker available128- **Use Spring Cloud Contract** when: Spring Boot ecosystem, provider-driven workflow preferred129- **Use OpenAPI validation** when: Spec-first design, simple request/response validation sufficient130131**Test generation depth**:132133- **T1 only** when: Single endpoint, proof-of-concept, immediate feedback needed134- **T2** when: Production system, CI integration required, 3-10 endpoints135- **T3** when: Complex versioning, multiple consumers, governance required, >10 endpoints136137**Breaking change severity**:138139- **Block deployment** if: Removed endpoints used by active consumers, required field deleted140- **Warn but allow** if: New optional field, added endpoint, relaxed validation141- **Auto-approve** if: Only documentation changes, no schema modifications142143**Ambiguity thresholds**:144145- If `api_spec` has >20 endpoints, request focus on specific consumer-provider pair146- If breaking changes detected but no previous contract available, emit warning and proceed147- If circular dependencies detected (A depends on B, B depends on A), emit error and abort148149---150151## Output Contract152153**Required fields** (all tiers):154155```json156{157 "contract_tests": {158 "type": "code",159 "language": "javascript|java|python|go",160 "framework": "pact|spring-contract|openapi",161 "file_path": "path/to/test/file",162 "content": "// Full test code..."163 },164 "contract_spec": {165 "type": "json|yaml",166 "format": "pact_v3|spring_contract_dsl|openapi_3.1",167 "content": "{ ... contract JSON ... }"168 }169}170```171172**T2+ additional fields**:173174```json175{176 "ci_integration": {177 "type": "yaml",178 "pipeline": "github_actions|gitlab_ci|jenkins",179 "content": "# Pipeline config..."180 },181 "validation_report": {182 "type": "markdown",183 "breaking_changes": [184 {185 "severity": "critical|warning|safe",186 "description": "Removed endpoint /users/:id",187 "affected_consumers": ["mobile-app", "web-ui"]188 }189 ],190 "compatibility_matrix": "table of consumer/provider version compatibility"191 }192}193```194195**T3 additional fields**:196197```json198{199 "versioning_plan": {200 "type": "markdown",201 "strategy": "url|header|content_negotiation",202 "migration_steps": ["step 1", "step 2"]203 },204 "governance_workflow": {205 "type": "markdown",206 "approval_process": "description",207 "pact_broker_config": "webhook and notification setup"208 }209}210```211212---213214## Examples215216**Example 1: Pact Consumer Test (JavaScript, ≤30 lines)**217218```javascript219const { PactV3, MatchersV3 } = require('@pact-foundation/pact');220const { getUserById } = require('./api-client');221const provider = new PactV3({ consumer: 'mobile-app', provider: 'user-service' });222describe('User API Contract', () => {223 it('gets user by ID', () => {224 provider225 .given('user 123 exists')226 .uponReceiving('a request for user 123')227 .withRequest({228 method: 'GET',229 path: '/users/123',230 headers: { Accept: 'application/json' },231 })232 .willRespondWith({233 status: 200,234 headers: { 'Content-Type': 'application/json' },235 body: {236 id: MatchersV3.like(123),237 name: MatchersV3.like('Alice'),238 email: MatchersV3.email('alice@example.com'),239 },240 });241 return provider.executeTest(async (mockServer) => {242 const user = await getUserById(mockServer.url, 123);243 expect(user.name).toBe('Alice');244 });245 });246});247```248249See `/skills/api-contract-testing/resources/` for Spring Cloud Contract and OpenAPI examples.250251---252253## Quality Gates254255**Token budgets** (strict):256257- T1: ≤2000 tokens (single endpoint test generation)258- T2: ≤6000 tokens (multi-endpoint + CI + breaking change detection)259- T3: ≤12000 tokens (schema evolution + governance + versioning)260261**Safety requirements**:262263- All generated tests must be runnable or marked as pseudo-code264- No hardcoded secrets or production API keys in test code265- All URLs in contract specs must be localhost or mock servers266267**Auditability**:268269- All breaking changes must be logged with severity and affected consumers270- Contract evolution history must be traceable via Pact Broker or version control271- CI integration must include contract verification as blocking gate272273**Determinism**:274275- Same `api_spec` + `role` + `framework` must generate identical contract tests276- Breaking change detection must be idempotent (same input = same output)277278**Validation**:279280- Generated Pact JSON must validate against Pact JSON Schema v3281- OpenAPI contracts must validate against OpenAPI 3.1 spec282- Spring Contract DSL must compile without errors283284---285286## Resources287288**Official Documentation** (accessed 2025-10-26T06:31:34-04:00):289290- [Pact Documentation](https://docs.pact.io/) - Consumer-driven contract testing291- [Pact Specification v3](https://github.com/pact-foundation/pact-specification/tree/version-3) - Pact JSON format292- [Spring Cloud Contract Reference](https://docs.spring.io/spring-cloud-contract/reference/) - Provider-driven contracts293- [OpenAPI Specification 3.1.0](https://spec.openapis.org/oas/v3.1.0) - API schema standard294- [Swagger API Validation](https://swagger.io/docs/specification/about/) - OpenAPI validation tools295296**Tools and Libraries**:297298- [Pact Broker](https://docs.pact.io/pact_broker) - Contract storage and verification299- [pactflow.io](https://pactflow.io/) - Managed Pact Broker service300- [openapi-validator](https://www.npmjs.com/package/express-openapi-validator) - Express.js OpenAPI validation301- [jest-pact](https://github.com/pact-foundation/jest-pact) - Jest integration for Pact302303**Best Practices**:304305- [Zalando RESTful API Guidelines](https://opensource.zalando.com/restful-api-guidelines/) - API versioning and evolution306- [Microsoft API Design Guidance](https://learn.microsoft.com/en-us/azure/architecture/best-practices/api-design) - Breaking change management307- [Martin Fowler: Consumer-Driven Contracts](https://martinfowler.com/articles/consumerDrivenContracts.html) - Contract testing patterns308309**Example Repositories**:310311- [Pact Examples (Node.js)](https://github.com/pact-foundation/pact-js/tree/master/examples)312- [Spring Cloud Contract Samples](https://github.com/spring-cloud-samples/spring-cloud-contract-samples)