validating-api-contracts
Validate API contracts using consumer-driven contract testing (Pact, Spring Cloud Contract). Use when performing specialized testing. Trigger with phrases like "validate API contract", "run contract tests", or "check consumer contracts".
What this skill does
# 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
1. 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.
2. 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.
3. 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.
4. 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.
5. 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.
6. 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.
7. 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):**
```typescript
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('[email protected]'),
});
})
.executeTest(async (mockServer) => {
const response = await fetch(`${mockServer.url}/api/users/1`);
const user = await response.json();
expect(user.name).toBeDefined();
});
});
});
```
**Provider verification test:**
```typescript
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: '[email protected]' });
},
},
}).verifyProvider();
});
});
```
**can-i-deploy CI check:**
```bash
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
- Pact documentation: https://docs.pact.io/
- PactFlow (managed Pact Broker): https://pactflow.io/
- Spring Cloud Contract: https://spring.io/projects/spring-cloud-contract
- openapi-diff: https://github.com/OpenAPITools/openapi-diff
- Consumer-Driven Contracts: https://martinfowler.com/articles/consumerDrivenContracts.html
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.