1. Home
  2. Blog
  3. Test Automation

Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

When one team changes an API, another team’s app can break without anyone noticing until production. Contract testing checks that both sides still agree, without running the whole system. We tested five realistic API changes against a contract to show which ones break consumers.

10 min read
API contract testing explained: catch breaking changes before they ship

Key takeaways

  • A contract is the agreed shape of requests and responses between an API provider and its consumers.
  • Contract tests check each side against that agreement separately, so you do not need every service running.
  • In our check, adding a field passed, while renaming a field, changing a type or adding an enum value failed.
  • Consumer-driven contracts, often with Pact, test only what consumers actually use.

The orders team renames total to amount because it reads better. Their own tests pass, and they deploy. Ten minutes later the mobile app shows every order as costing nothing, and the invoice service crashes. Each team tested its own code, but nobody tested the agreement between them. That gap is what contract testing fills.

We built a small contract as a JSON Schema and checked five realistic provider responses against it with the Python jsonschema library (version 4.26). The results below come from that run. Pact and OpenAPI tooling are described from their documentation; we did not run them for this article.

The problem with testing services in isolation

In a system of many services, each team writes unit tests and API tests for its own service. Those tests use the team’s own idea of what other services send and expect, often as mocks. When a provider changes, the consumer’s mocks still return the old shape, so the consumer’s tests keep passing. The mismatch is only discovered when both versions meet in a shared environment or in production. Full end-to-end tests can catch it, but they are slow, fragile and need everything deployed together.

What is contract testing?

Contract testing checks that two parties, a consumer that calls an API and a provider that serves it, agree on how they communicate: endpoints, methods, headers, request bodies, response fields, types and status codes. The agreement is written down as a machine-readable contract. Each side is then tested against the contract on its own: the consumer against a mock built from the contract, and the provider by replaying the contract’s requests against the real service.

Compared with other test types

Test type Checks Needs other services running?
Unit test Internal logic No
API / functional test One service’s behaviour Usually not
Contract test Agreement between two services No
Integration test Real services working together Yes
End-to-end test Whole user journey Yes, everything

Contract tests sit between API tests and integration tests in the test pyramid. They are nearly as fast as unit tests but catch problems that previously needed integration environments.

A contract check we ran

Here is a simple contract for an order response, written as a JSON Schema:

contract = {
  "type": "object",
  "required": ["id", "status", "total"],
  "properties": {
    "id":     {"type": "integer"},
    "status": {"enum": ["paid", "pending", "refunded"]},
    "total":  {"type": "number", "minimum": 0}
  }
}

We validated five versions of the provider’s response:

v1 provider              PASS
v1 + new field           PASS
renamed total->amount    FAIL: 'total' is a required property
id as string             FAIL: '101' is not of type 'integer'
new status value         FAIL: 'on_hold' is not one of ['paid', 'pending', 'refunded']

Adding a currency field was safe, because consumers ignore fields they do not know about. Renaming total, sending the ID as text, and introducing a new status value all broke the contract. Each of these would have passed the provider’s own tests.

Breaking vs safe changes

Change Usually breaking?
Add an optional response field No
Add a new endpoint No
Remove or rename a response field Yes
Change a field’s type or format Yes
Make an optional request field required Yes
Add a new enum value in a response Often, if consumers handle values strictly
Change status codes or error format Yes
Tighten validation on inputs Often

The enum case is subtle. Adding on_hold looks harmless to the provider, but a consumer with a switch statement over known statuses may crash or show nothing. Well-written consumers handle unknown values gracefully, and contracts make that expectation explicit. For versioning strategies when a breaking change is unavoidable, see semantic versioning and our REST API best practices.

Consumer-driven contracts

In consumer-driven contract testing, each consumer writes down exactly what it needs from the provider: the requests it makes and the fields it reads. The provider must satisfy every consumer’s contract. This has a big advantage: a provider can freely change or remove anything that no consumer uses, and it knows exactly which consumer would break if it changes something that is used.

Our demo checked a single schema, which is closer to the provider-driven style. A real consumer-driven contract would usually list only the fields that consumer actually reads, so a field used by nobody could be removed without any failure.

Tip: Contracts should describe what a consumer needs, not everything a provider returns. A contract that pins every field and exact value becomes a brittle copy of the provider’s tests, failing on harmless changes and eroding trust.

How Pact works

Pact is the most widely used consumer-driven contract tool, with libraries for many languages. The flow, from its documentation:

  1. Consumer test: the consumer’s unit tests call a Pact mock server, declaring each expected request and the minimal response they need.
  2. Pact file: those expectations are saved as a JSON contract, the “pact”.
  3. Share: the pact is published to a Pact Broker or PactFlow.
  4. Provider verification: the provider’s CI fetches all pacts, replays each request against the real provider, and checks the responses.
  5. Can I deploy? Before deploying either side, a check confirms that the versions about to run together have verified contracts.

Provider states, such as “order 101 exists”, let the provider set up test data for each interaction. This is where most teams spend their effort when adopting Pact.

Provider-driven contracts with OpenAPI

Many teams start from the other direction: the provider publishes an OpenAPI specification, and tests check that the real API matches it, and that consumers only use what it describes. Tools can validate live responses against the spec, generate tests from it, or compare two versions of the spec and flag breaking changes. This works well for public APIs with many unknown consumers, where collecting consumer contracts is impossible. The trade-off is that it checks the grammar of messages, not which parts any consumer actually relies on.

Contract tests in CI

  • Consumer pipeline: run consumer contract tests and publish the contract on every change.
  • Provider pipeline: verify against all consumer contracts on every change; fail the build on any break.
  • Before deploy: check compatibility between the exact versions going to each environment.
  • Webhooks: when a consumer publishes a changed contract, trigger the provider’s verification immediately.

Fitting this into a CI/CD pipeline turns “did we break anyone?” from a meeting into a build status.

Pitfalls

  • Over-specifying: asserting exact values instead of types and required fields makes contracts brittle.
  • Treating contracts as functional tests: a contract checks shape and agreement, not business correctness. Keep functional tests too.
  • Skipping provider states: without realistic setup data, verification passes for the wrong reasons.
  • No ownership: someone must own the broker and respond when verifications fail.
  • Forgetting asynchronous messages: events on queues are contracts too, and tools like Pact support message contracts.

When to use contract testing

Contract testing pays off when several teams own services that call each other, deployments are independent, and integration environments are slow or unreliable. For a single team with one API and one front end deployed together, good API tests may be enough. Our API testing guide covers that starting point.

Getting started without boiling the ocean

  1. Pick one pair: the consumer and provider whose integration breaks most often, or matters most.
  2. Write the consumer’s expectations for two or three key interactions, asserting only the fields it reads.
  3. Verify the provider against them locally, fixing provider states until it passes for the right reasons.
  4. Add both sides to CI, so either team learns within minutes when it breaks the agreement.
  5. Review after a few weeks: did it catch anything, and did anything break that it missed? Then extend to the next pair.

Starting small keeps the effort visible and builds trust. Teams that try to put every service under contract at once often stall on tooling and test data before seeing any benefit.

Final thoughts

Contract testing catches the breaking changes that each team’s own tests cannot see: renamed fields, changed types and new enum values. Start with one important consumer-provider pair, keep contracts focused on what the consumer really uses, verify the provider in CI, and add a deployment check. In our simple test, three of five plausible changes would have broken consumers, all invisible to the provider’s own suite.

Frequently asked questions

What is API contract testing?

Testing that an API provider and its consumers agree on request and response formats, by checking each side separately against a shared contract instead of running all services together.

What is consumer-driven contract testing?

An approach where each consumer defines the requests it makes and the fields it needs. The provider is verified against all consumer contracts, so it knows which changes would break someone.

What is Pact?

Pact is a popular open-source tool for consumer-driven contract testing. Consumer tests generate contract files, which the provider then verifies against its real implementation.

Is adding a field a breaking change?

Adding an optional response field is usually safe; in our test it passed. Renaming, removing or changing the type of a field breaks consumers.

Does contract testing replace end-to-end tests?

It replaces many of them, especially those used only to check that services can talk. Keep a few end-to-end tests for critical user journeys.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →