Skip to navigation

Claude Code Contract Tests: Check API Expectations

In short: Turn consumer expectations into provider checks, version the contract, and separate compatibility evidence from schema guesses.

Published 19 min read
On this page

Direct answer

Write down the API interactions a consumer actually relies on, verify the provider against that record, and treat the result as compatibility evidence rather than proof of integration. Pact describes itself as a consumer-driven contract testing tool whose contract is generated during automated consumer tests, and it uses contract by example: the contract covers the parts of the communication that consumers actually use.

The workflow is four moves. Identify one consumer interaction and name the fields it depends on. Capture the expectation before the provider changes. Verify the provider against the captured expectation. Classify the compatibility impact and choose a version increment from that evidence.

A contract is narrower than an integration test, and narrower on purpose. It says nothing about interactions nobody recorded, provider state that was never modeled, or deployment behavior. SemVer requires a major increment for an incompatible public API change, and the compatibility decision belongs to the team that has declared what its public API is.

Why undocumented API expectations break silently

A provider change usually starts from the provider’s code. A field is renamed, a nullable value becomes non-nullable, a list starts being returned empty instead of null. Every one of those is invisible in the provider’s own tests if no consumer asserted on the old shape.

The failure surfaces later, in a consumer that was never run against the new provider. That is what makes cross-team API changes expensive: the defect is discovered by someone who did not make the change, often after deployment. The cost is not only the fix. It is the coordination required to find out who depended on the old shape and how many of them there were.

An explicit contract changes the discovery point. The consumer’s expectation is recorded as an artifact, and the provider verifies against it before the change merges. A breaking change is then found by the provider’s own verification run, by the team that made the change, while it is still cheap to fix.

The economic framing is the one the cost per verified change guide uses: a check that runs before merge is a different unit of cost from one that runs after deployment. A contract moves a class of failure from the second category to the first.

Evidence map from a consumer interaction to a captured contract, provider verification, and a compatibility decision.
Editorial evidence map based on F010, F011, and F012. A contract records an interaction, not the whole system, and unused interactions sit outside the evidence.

Evidence and its limits

Official, F010: Pact describes itself as a consumer-driven contract testing tool whose contract is generated during automated consumer tests. This describes Pact’s model. It is not a claim about every contract-testing approach, and it does not say the generated contract is complete.

Official, F011: The same documentation explains that Pact uses contract by example and tests the parts of communication actually used by consumers. This is the reason unused interactions are outside the contract’s evidence. Adding an interaction nobody uses would not widen the guarantee.

Official, F012: Semantic Versioning 2.0.0 requires a major increment for an incompatible public API change. The repository must first define its public API and its compatibility policy. SemVer classifies the change; it does not determine whether a specific change is incompatible.

Official: The Pact five-minute guide and how Pact works describe the consumer and provider roles. Claude Code best practices supports giving the agent a pass-or-fail check, which is the shape a verification run takes.

No claim here treats a contract test as integration coverage. No provider state, deployment behavior, or cross-service correctness is asserted, and no benchmark for defect reduction is cited.

Identify the consumer interaction

Start with one consumer and one interaction, not with the API as a whole. An interaction is a request the consumer makes and the parts of the response it depends on. The useful boundary is dependence: a field the consumer ignores does not belong in the contract, because the consumer cannot break if that field changes.

Consumer Interaction Request fields that matter Response fields that matter Owner
Cart summary Fetch a customer discount customer ID, cart total discount rate, currency, applied flag Billing team
Invoice renderer Fetch a finalized invoice invoice ID line items, total, issued timestamp Billing team
Order export Fetch order line items order ID, page token items, next page token Orders team
Mobile app Fetch a session credentials token, expiry, scopes Platform team

Two habits keep this step honest. Name the owner, because a contract without an owner is a contract nobody will update. Record only fields the consumer reads, because a contract padded with unused fields creates maintenance work and a false sense of coverage.

The distinction between a field the consumer reads and one it should tolerate is a design decision. A consumer that reads a free-text note field has made that field part of its contract, even if the note seems incidental. Recording the dependence is how the provider learns which changes need a compatibility review.

Write the expectation before the provider change

Capture the expectation while the current behavior still exists. A contract written after the provider changes tends to describe the new shape, which makes it a description of the change rather than a check on it. The generated tests oracle bias guide describes the general version of this problem: an artifact produced from the implementation cannot act as an independent standard for it.

The expectation has three parts. The request the consumer sends, including the fields that must be present and the state they represent. The response the consumer needs, including the fields, their types, and any constraints the consumer relies on such as non-null or a specific format. Any matching rule the consumer depends on, such as an error status for a missing resource.

Write the expectation as a test that runs against a mock or stub provider, so it produces a pass-or-fail result and an artifact. The artifact is the contract. That fits the pass-or-fail loop described in the official Claude Code best practices guidance: the agent can run the consumer test and report the result, and the artifact it produces is reviewable.

A generated contract still needs review. Read the recorded request and response and confirm they match what the consumer code actually does. A field recorded because a test helper added it, rather than because the consumer reads it, is noise that will constrain the provider for no benefit.

Workflow from identifying a consumer interaction to capturing the expectation, verifying the provider, and recording the compatibility decision.
Editorial workflow based on F010, F011, and F012. Capturing before the provider change is what makes the contract a check rather than a description.

Generate and review the contract

The contract is generated when the consumer test runs. Pact’s model behind F010 is that the consumer test writes the interactions to a file, and that file becomes the artifact the provider verifies against. The five-minute guide describes this consumer-then-provider sequence.

Review the generated file the way a reviewer reads a diff:

Contract element Review question Failure mode if skipped
Request path and method Does the consumer actually call this? Contract constrains an endpoint nobody uses
Required request fields Does the consumer send each one? Provider must accept fields that never arrive
Response fields Does the consumer read each one? Provider blocked from removing dead fields
Types and constraints Does the consumer rely on them? Breaking change recorded as compatible
Error matching Does the consumer handle this status? Error behavior changes without a signal

The review is where a contract earns its value. An unreviewed contract can be simultaneously too strict, blocking a safe provider change, and too loose, missing the field a consumer actually depends on. The snapshot review guide covers the same review discipline for stored output: read the delta rather than accepting the update.

Keep the contract in version control next to the consumer, and treat a change to it as a change to a public interface. That is what makes the compatibility decision in the next section possible.

Run provider verification

Provider verification replays each recorded interaction against the real provider and checks that the response satisfies the expectation. A verification failure means the provider would break that consumer. This is the pass-or-fail check that closes the loop for the provider team.

Verification has a deliberate boundary. It checks the interactions that were recorded, against the provider state that the verification set up. It does not exercise the consumer against the provider, and it does not model the provider’s production state or deployment behavior. Two services passing verification can still fail in production for reasons the contract never captured.

Provider change Contract result Compatibility decision Version impact
Optional field added Pass Compatible addition Minor
Field made non-nullable Fails where nil was expected Incompatible for that consumer Major, or fix the provider
Error status changed Fails on the error match Incompatible Major, or preserve the old status
Internal refactor, same shape Pass No consumer impact Patch
New endpoint No contract exists Not yet covered Minor, add a contract

The verification run is a good fit for the agent loop. Give it the verification command and the failing interaction, and ask for the command output and the exact field that did not match. The test selection guide covers placing this check in the run order, and a verification that only fails on a specific consumer’s contract belongs in the set for any change to that endpoint.

Tradeoff between narrow contract evidence that runs early and the integration behaviors it does not cover.
Editorial tradeoff diagram based on F010 through F012. Contract evidence runs early and cheaply; it does not replace integration testing, and unused interactions stay uncovered.

Classify the compatibility impact

A verification failure is not automatically a major version. It is a signal that a recorded expectation no longer holds, and the classification depends on whether the change is incompatible for the declared public API.

SemVer behind F012 assigns a major increment to incompatible public API changes, a minor increment to backward-compatible additions, and a patch increment to compatible fixes. Applying that requires knowing which parts of the provider’s surface are public and which consumers are supported. A change that breaks an internal client with no external contract may be a refactor. The same change against a published API is a major.

Signal Classification question Typical increment
Field removed or renamed Can an existing consumer still work? Major
Constraint tightened Does any recorded expectation now fail? Major if a contract fails
Optional field added Do existing expectations still pass? Minor
Behavior fix with same shape Do all contracts still pass? Patch
Error contract changed Do error matches still pass? Major if a contract fails

The classification should be recorded with the evidence behind it: which contracts were run, which failed, and what was changed to make them pass. The SemVer decision guide covers the general version of this decision, including the caution that diff size is not evidence of compatibility. A one-line change can be a major, and a large internal refactor can be a patch.

When the change is genuinely incompatible, the provider has two honest options: increment the major version, or preserve the old behavior alongside the new one until consumers migrate. Hiding an incompatible change in a patch release is the failure mode the compatibility decision guide warns against, and a contract failing in verification is exactly the evidence that prevents it.

Version contracts with the API

A contract describes an expectation at a point in time, and it should be versioned alongside the interface it describes. A provider that supports two API versions may need to satisfy two generations of contract, and a contract that is silently updated can hide the transition.

Three practices keep the versioning coherent. Store the contract with the consumer, so a provider change that breaks it is visible in the consumer’s repository. Record which provider version each contract was verified against, so a later reader can tell whether the evidence is current. Treat a contract change as an interface change, and put it through the same review as the provider code.

The release tags guide covers fixing which revision a verification applied to, and the release checklist guide covers connecting that identity to the checks that ran. A contract verified against an unreviewed revision is not evidence about the release.

Control checklist covering consumer interaction scope, reviewed contract, provider verification, and recorded version decision.
Editorial control checklist derived from F010 through F012. Passing the checklist shows the compatibility evidence was recorded; it does not prove end-to-end integration correctness.

Use Claude Code to inspect missing coverage

The agent is useful at the edges of a contract, where the question is what nobody recorded. Give it a consumer and an endpoint, and ask which response fields the consumer code reads and which error statuses it handles. Compare that list with the recorded contract. Fields read but not recorded are a coverage gap, and fields recorded but not read are noise.

Ask the same question in the other direction for the provider. A provider endpoint with no contract attached has no consumer-driven evidence, which is a fact worth knowing before a change is proposed. The gap is not a defect by itself. It means a change to that endpoint will not be caught by this mechanism, and the team should decide whether to add a contract or accept the risk.

Two cautions apply. Generated coverage suggestions come from reading code, and code can read a field dynamically in a way a search misses. Review each suggestion rather than accepting the list. And a larger contract is not a better contract. Adding interactions nobody uses enlarges the maintenance surface without widening the evidence, which is the trap behind F011.

The property tests guide covers a complementary technique when the risk is a class of inputs rather than a missing field: state an invariant over the response and let bounded generation search for a violation.

Record what the contract does not test

The honest part of a contract is the list of things it cannot say. Recording that list is what stops a green verification run from being read as integration coverage.

Contract check Integration check Uncovered behavior
Recorded request matches expectation Real consumer against real provider Interactions nobody recorded
Response satisfies recorded fields Full request and response lifecycle Provider state and data dependencies
Error status matches the match rule Error handling across the real path Cascading failures across services
One consumer at a time Several consumers together Combined load and ordering effects
Provider code as deployed in verification Provider as deployed in production Configuration and environment differences

Provider state deserves explicit mention. A verification sets up the state it needs to replay an interaction. Production state is different, and the contract says nothing about how the provider behaves under data the verification never created. The async races guide covers a related gap on the consumer side, where ordering between two calls is not captured by either contract alone.

Deployment behavior is also outside the evidence. A contract verified against a provider running locally says nothing about the provider as configured in production. The rollback plan guide covers the separate discipline of planning an inverse change, which is where deployment assumptions belong.

Verdict that a reviewed, versioned contract catches an incompatible provider change early while leaving integration and deployment behavior untested.
Editorial verdict based on F010 through F012. The benefit is an early, owned compatibility signal; the unresolved limitation is that a green verification run is not integration coverage and unused interactions stay outside the evidence.

Worked example: a discount field becomes non-nullable

Suppose a provider team changes a discount rate from nullable to non-nullable, because the new pricing logic always computes a value. The cart summary consumer recorded a contract that expects the rate field and does not assert nullability. The invoice renderer recorded a contract that expects the field to accept null for pending invoices.

Verification runs both contracts. The cart contract passes, because a non-nullable rate satisfies an expectation that never required null. The invoice contract fails, because the recorded match allows null and the provider no longer returns it.

Consumer Contract result Compatibility decision Version impact
Cart summary Pass Compatible for this consumer No consumer-driven major
Invoice renderer Fail on null match Incompatible for this consumer Major, or keep null for pending invoices

The failure is caught by the provider team before merge, with the exact consumer and field named. The concrete win is that an incompatible change is discovered by the team that made it rather than by the invoice team after deployment. The concrete loss is that the contract covers only the recorded interactions: a consumer that reads the rate field dynamically, or one that was never recorded, is not protected by this run.

Contracts sit at the boundary between two codebases, and the surrounding guides cover the rest of that boundary. Snapshot review discipline covers reading a stored expectation before accepting a change to it. Deterministic tests covers the clock and randomness that would otherwise make a recorded interaction unreproducible. Property tests cover the input classes a single recorded example cannot reach.

On the consumer side, selecting checks for changed code places verification in the run order, and triaging flaky tests applies when a verification fails only sometimes. Mutation testing covers a contract that passes whether or not the provider changed. Test fixtures that isolate state covers the provider state a verification sets up.

On the release side, choosing a semantic version, tagging the reviewed candidate, and connecting the release checklist turn compatibility evidence into a version decision. Atomic commits and commit messages that encode intent keep the contract change and the provider change traceable together. At merge time, choosing a branch policy and defining merge checks decide whether verification is enforced.

Stop conditions and follow-up

Stop and revisit the contract when verification fails and the recorded expectation turns out to describe something the consumer never relied on. The fix is to narrow the contract, not to change the provider. Stop and escalate when a verification failure indicates a genuine incompatibility for a supported consumer, because that is a version decision with external consequences. Stop and record a gap when an endpoint has no contract and no consumer-owned evidence.

Follow-up takes three forms. A failing contract should be either satisfied or deliberately renegotiated with the consumer’s owner, and the renegotiation is an interface change. A contract that passes against an unreviewed revision should be rerun against the reviewed candidate. A missing contract on a changing endpoint should be added before the next change, while the current behavior is still available to record.

For the wider release path, deciding major, minor, or patch is the decision this evidence feeds, and recovering a failed merge group covers the case where a verification failure blocks a grouped merge.

Data gap and future update

No measured reduction in integration defects, deployment failures, or coordination cost appears in the source set for this post. Pact’s self-description behind F010 and F011 is a description of its model, not a measured effect, and no benchmark is cited. SemVer behind F012 classifies changes; it does not measure outcomes.

The source set contains no specific API, no published contract, and no provider state model, so every example here is illustrative. A future update should add three things. A measured comparison of consumer-driven contracts against integration testing alone on a real system. A documented pattern for rotating and expiring contracts as provider versions change. Fresh content review of the Pact documentation for the version a reader is likely to run, since the five-minute guide and the how-it-works page were checked for reachability rather than fully reviewed.

One AI API Key option for OpenAI-format agents

Claude Code uses an Anthropic-format route, so the One AI free model IDs are not a Claude Code model source. The packet records Claude IDs as unavailable on 2026-11-27.

For a separate OpenAI-format agent, One AI API Key offers https://api.oneaiapikey.com/v1, one key, and 46 live free IDs. That is a different client and request format, not a workaround for Claude Code authentication. Review the free model list and eligibility notes before choosing an agent route.

FAQ

Does a passing contract verification mean the integration works?

No. F010 and F011 describe a contract as a record of the interactions a consumer uses, verified against the provider in isolation. It does not exercise the consumer against the provider, model production state, or cover interactions nobody recorded. Treat it as compatibility evidence with a stated scope.

Should I add every field to the contract to be safe?

Adding fields the consumer never reads widens the maintenance surface without widening the evidence, because F011 limits the guarantee to interactions actually used. Record the fields the consumer depends on and review the generated contract to remove noise.

When does a contract failure require a major version?

A major increment is required when the change is incompatible for the declared public API, per F012. A failing contract is evidence that at least one supported consumer’s expectation no longer holds. The team still has to decide whether to increment the major version or preserve the old behavior alongside the new.

Can Claude Code write the contract for me?

It can run the consumer test that generates the contract and report the pass-or-fail result, which fits the pass-or-fail loop in the official best practices guidance. The generated artifact still needs review against what the consumer code actually reads, since an unreviewed contract can be both too strict and too loose.

What is the difference between a contract test and an integration test?

A contract checks one recorded interaction against the provider in isolation, and it runs early and cheaply. An integration test exercises the consumer and provider together and can cover behavior the contract never recorded. They answer different questions, and a green verification run does not replace integration coverage.

More Claude Code troubleshooting

Sources

More in Blog

Try it

One API key for GPT, Grok, DeepSeek, Kimi, GLM, MiniMax, Qwen, Step, Beam, Nemotron, ERNIE, Hunyuan, Gemma, Laguna, LFM, LongCat, Llama, Solar, Jais, Mistral, K2 and Roleplay.

One AI API Key speaks the OpenAI and Anthropic formats, so you change the base URL and the key, not your code. Credit packs start at $10, and every model has a published per-token rate.

New accounts$10 credit on sign-up
  • 100requests
    per day
  • 3Mtokens
    per day
  • 47free
    models
  • $0per
    token
  • No card
  • No end date
Claim $10 credit →