API tests

Contract testing: prevent an API change from breaking its clients

Consider this illustrative scenario: a team renames a field in an API response, the service tests pass, and the team deploys the change. Three hours later, another team calls because orders have stopped coming through. Their application was reading the original field. Contract testing records these dependencies as an automatically verifiable agreement and can flag incompatibility before release. It is particularly useful when separate teams develop and deploy the API and its clients.

Who the client is and what a contract checks

The client here is an application that uses the API. In an HTTP integration, it sends requests and is called the consumer. The API provider processes them and returns responses. A service can be a provider to a mobile application and a consumer of a payment service.

With a contract driven by the consumer, the client records a specific request and the expected response. To retrieve an order, for example, it needs status code 200, the orderId field, and a status value that determines its next action. The contract captures those requirements. It does not automatically describe the whole API. Pact’s documentation explains how the two sides are tested.

Ordinary tests can miss the problem when the provider checks its new response while the client still uses an old mock, or simulated response. Both suites pass, but they check different agreements. Contract testing connects the client’s expectation to a check of the actual API without requiring every service to run together.

How this differs from schemas, functional tests and E2E tests

Each layer answers a different question:

Layer What it checks for an order
OpenAPI and schema validation Which requests, responses and data types the interface describes, and whether the checked data conforms to them.
A particular client’s contract Whether the client creates the agreed request, handles the expected response, and the provider can fulfil that expectation.
Functional API test Whether the service calculates the price correctly, saves the order, or rejects an unauthorised operation.
E2E test Whether a user completes an order through the connected parts of the system.

OpenAPI describes an interface and can support contract checks. Schema compliance alone does not prove that a particular client handles a response correctly. A new response can conform to an updated schema and still break an older client.

You need functional tests for service logic, authorisation rules and boundary values. Pact distinguishes message agreement from checking an operation’s effects, such as whether an order was actually saved. E2E, or end-to-end tests, also check how components work together across a complete process. A contract alone does not confirm the network setup, production access configuration, or the entire purchase journey. The article on testing REST APIs covers the scope of a functional suite.

Preparing tests on both sides

On the consumer side, the test calls the application’s own code that communicates with the API, with its address set to the Pact mock server. It checks the request produced and how the client handles the prepared response. A manually written request in the test is insufficient if it bypasses the actual client code. A passing result could hide an error in parameter construction or field parsing. The consumer testing guidance stresses this approach.

The provider then replays the contract’s requests against its own running implementation and compares the actual responses with the expectations. For early feedback, run it locally or during continuous integration (CI), which builds and tests the application after code changes. Substituting prepared JSON for its response would leave the implementation untested.

You can replace downstream services with controlled responses. Keep the request processing and validation that you intend to test, though. Pact’s provider verification guidance warns that stubbing layers before input processing can conceal an invalid request.

In the illustrative example, removing orderId should violate the expectation of a client that reads it. If only the consumer test against the mock passes and the provider test never runs, half of the check is missing.

Data and provider states without ordering dependencies

An order must exist before a test can retrieve it. A provider state describes this precondition, such as “order 123 exists”. The provider prepares the corresponding data before verification. For another interaction, it can prepare the state “order 123 does not exist” and verify the expected error response.

Provider states describe preconditions on the provider side. Verify each interaction independently. Do not depend on a preceding test having created the order. Changing the execution order or running tests in parallel would make that dependency a source of intermittent failures.

Agree on data isolation and cleanup after each test. Parallel runs must not overwrite the same order. State setup should be repeatable and available in the test environment. When a test fails, distinguish an unmet contract from a data setup error, such as an unavailable database.

Where to match exactly and where to use a matcher

A fixed comparison of the entire response, or snapshot, can fail when a timestamp, identifier, or field the client never uses changes. A matcher is a matching rule, such as “the value is a string” or “it has the required format”. Choose it according to the client’s dependency rather than every property of today’s response.

For orderId, checking the required type may be enough. For status, a string check is insufficient if the client only handles paid and cancelled. You need examples and assertions for the meaning its behaviour depends on. Similarly, a number check alone does not protect against a switch from euros to cents.

Pact’s response matching ignores unexpected fields. That does not mean adding a field is compatible with every client. A strict parser may reject an unknown field. Check its behaviour through the actual client code and a separate test using an extended response. The matcher rules and parser rules need to reflect the same agreement.

Versions and the decision before deployment

The contract file alone cannot determine whether to release. You need to know which client version produced it and which provider version successfully verified it. Pact Broker brings those contracts and results together. After a successful deployment, record the version and environment there too, following the deployment and release recording guidance.

Before deployment, can-i-deploy checks a specific candidate version against the versions recorded in the target environment. The documentation for this check describes the results matrix between consumers and providers. Its answer depends on precise versions, complete records, and successful required verifications.

The provider should verify contracts for relevant clients, including currently deployed versions and released versions that remain supported. A mobile application user may still run an older version after a new one is released. Checking only the newest client does not protect that user. Pact also recommends the mainBranch and deployedOrReleased selectors for selecting contracts.

A missing result is not confirmation of compatibility. Find out whether verification is still running, never started, or did not publish its result. The Broker CLI can poll for missing results. However, dry-run returns a successful exit code even when deployment is not approved. Use it to check that the integration is wired correctly, rather than as an effective release gate.

Changing an API without switching every client at once

When renaming a field, first plan a transition during which the API retains the original field and supports the new one. Verify that relevant clients accept this response. Then update clients gradually, publish their contracts, and verify them against the necessary provider versions.

Remove the original field only in line with the agreed support policy and after confirming that relevant supported versions no longer depend on it. If the fields cannot coexist, consider a new versioned interface. A passing contract for the newest client is no reason to stop supporting every older one.

With a public API, you do not know every client or have its contract. Pact also identifies this limit in its guidance on suitable integrations. You also need documented compatibility rules, versioning, and an announced process for ending support. Contracts for known clients provide part of the protection. They do not prove that a change is safe across the entire public interface.

A pilot, ownership and maintenance costs

Start with one important integration where both teams know the client code and the provider. In an illustrative pilot, verify that:

  1. The client retrieves an existing order and handles the agreed fields correctly.
  2. It handles the agreed error response for a nonexistent order.
  3. Deliberately removing a field it uses causes provider verification to fail.
  4. The check before deployment distinguishes successful, failed, and missing verification of relevant versions.

Decide who maintains consumer tests, who prepares provider states, and who handles a blocked release. Track verification duration, diagnosis time, and checks that fail because of irrelevant differences. Adjust those checks to the client’s actual dependency. Avoid putting every provider functional scenario into every client’s contract.

When choosing a library, check language support and a shared contract specification version. Pact JS, for example, has an MIT licence. The library’s licence does not remove the work of adoption, broker operation, and test maintenance.

A well prepared pilot shows whether teams receive actionable information about incompatibility before deploying together. Extend it to other boundaries once you can trust the results and have assigned people to respond to failures.

Related topics

You might also be interested in

You can detect errors in the business logic more quickly directly through the API

Functional, integration and contract testing of REST, SOAP or GraphQL interfaces with the possibility of connection to the CI/CD pipeline.