~/qa-guides/api-contract-testing
>_ API Contract Testing: Consumer and Provider Examples
A catalog still returns 200 OK after its prices become strings. Follow one storefront request from the consumer test to the provider build that catches the break.
Short answer
API contract testing checks whether a client and a service agree on the requests and responses they exchange. In a consumer-driven HTTP test, the actual client sends a request to a mock service and uses the example response. Pact records that interaction. A provider test then replays the request against a running service build and compares its real response with the consumer's expectations.
Consider a storefront that reads a price in cents. Yesterday the catalog sent 1299. A new serializer sends "1299". The digits look identical in a log, and the endpoint still returns 200 OK. The storefront checks for an integer before showing a price, so this change breaks the product lookup. With a verified contract, the catalog team can see that failure in its own build.
Define what the storefront needs from the catalog
The consumer in this example is Storefront, specifically its HTTP adapter getProduct(baseUrl, sku). The provider is Catalog, the service that handles GET /products/P-17. Both interactions use that same method and path, send Accept: application/json, and expect a JSON response. What changes between them is whether product P-17 exists.
| State | HTTP | Client reads |
|---|---|---|
| Exists | 200 | An integer price in cents and currency equal to USD. |
| Missing | 404 | A code equal to PRODUCT_NOT_FOUND. |
This storefront sells in USD. Its adapter checks the currency, reads the numeric price, and returns a value the UI calls priceInCents. On a recognized product-not-found error it returns an unavailable state. It ignores additional properties, including marketing badges and human-readable error messages. These choices tell us which fields to put in the contract and where a change would affect the shopper.
Start with a real client call when choosing an interaction. Copying an entire catalog response into an assertion would make the provider maintain fields this client never reads. Conversely, checking only the status would miss both the amount type and the error code that control the client's behavior. The API test cases checklist has examples for choosing relevant success, error, and nullable-field cases.
Consumer example with Pact JS
The examples use Pact JS 17.1.4. In an async consumer test, import Pact and Matchers from @pact-foundation/pact, assert from node:assert/strict, and getProduct from the storefront code. The adapter takes a base URL so the test can point it at Pact's local mock. This exercises the same URL construction, request headers, JSON parsing, and error handling that the storefront uses.
Exercise a successful lookup
Create a pact with const pact = new Pact({ consumer: 'Storefront', provider: 'Catalog', dir: 'pacts' }). Use const wantsJson = b => b.headers({ Accept: 'application/json' }) to describe the outgoing header. Then define the first interaction in order.
const available = pact.addInteraction().given('P-17 exists').uponReceiving('a price lookup')const request = available.withRequest('GET', '/products/P-17', wantsJson)const fields = { price: Matchers.integer(1299), currency: 'USD' }const reply = request.willRespondWith(200, b => b.jsonBody(fields))
Run it with await reply.executeTest(checkPrice). Define checkPrice as an async function taking mock. Its first statement calls the adapter, and its second checks what the storefront receives.
const result = await getProduct(mock.url, 'P-17')assert.deepEqual(result, { state: 'available', priceInCents: 1299 })
The two uses of 1299 have different jobs. The consumer gets that specific example value, so reading it from the wrong field or converting it to dollars inside the adapter would fail the assertion. On the provider side, Matchers.integer(1299) asks for an integer. Tomorrow's correct catalog price could be different. The literal USD remains an exact expectation because this storefront uses that currency to interpret the number.
To check the request side, change only the SKU passed to the adapter to P-18 for one test run. The mock reported an unexpected request for /products/P-18 and an outstanding expected request for /products/P-17. Restore the original SKU before generating the contract used for provider verification.
Exercise the branch for a missing product
Use the same SKU for the missing-product test. Its provider state and expected response change together.
const missing = pact.addInteraction().given('P-17 is missing').uponReceiving('a missing product lookup')const lookup = missing.withRequest('GET', '/products/P-17', wantsJson)const absent = lookup.willRespondWith(404, b => b.jsonBody({ code: 'PRODUCT_NOT_FOUND' }))await absent.executeTest(checkMissing)
In the async checkMissing(mock) callback, read const result = await getProduct(mock.url, 'P-17') and check assert.deepEqual(result, { state: 'unavailable' }). An adapter that throws on every non-success status will fail this consumer test before it can interpret the error body. The machine-readable code matters because the storefront uses it to select the unavailable state.
After both tests pass, inspect pacts/Storefront-Catalog.json. In the example it contains two interactions, two provider states, and an integer matching rule at $.price in the successful response. Keep this generated file with the consumer revision that produced it. How Pact consumer testing and provider verification work
Provider example using the generated contract
Start the Catalog build under test on a local HTTP address. The example uses the real request handler and JSON serializer backed by a small in-memory inventory. Give the verifier the server's base URL and the path to the file from the consumer test. This lets the catalog team exercise the code that decides how a stored price appears on the wire.
Define stateHandlers with these two setup functions. Each establishes its own starting state before Pact sends the request.
- P-17 exists. Clear the test inventory and insert
P-17withpriceInCentsequal to the number1299and currencyUSD. Let the handler look up the record and serialize the response. - P-17 is missing. Clear the test inventory. Let the same handler take its normal missing-product path and produce the status and error body.
Import Verifier from @pact-foundation/pact. With the local server address in baseUrl and the pact file path in pactFile, run these statements in the provider test.
const options = { provider: 'Catalog', providerBaseUrl: baseUrl, pactUrls: [pactFile], stateHandlers }await new Verifier(options).verifyProvider()
For the existing product, Catalog should send JSON with status 200, an integer price, and the agreed currency. For the missing product it should send JSON with status 404 and the expected code. The handler can include its current explanatory message. If the first interaction receives a 404, confirm that the state setup inserted the product into the same inventory the running handler reads. If it receives 200 with the wrong type, inspect the response serializer. Pact JS provider verification and state handlers
Read the results from six provider runs
These runs used the same generated contract. Each row gives the verification result for the two interactions. The found and missing cases both kept their original HTTP statuses throughout.
| Variant | Found | Missing |
|---|---|---|
| Baseline | Pass | Pass |
| New badge | Pass | Pass |
| Price string | Fail at $.price | Pass |
| Error code | Pass | Fail at $.code |
| Wrong price | Pass | Pass |
| Repair | Pass | Pass |
New badge. Catalog adds "badge": "sale" alongside the original price and currency. Provider verification passes. Calling the actual storefront adapter against this version also returns priceInCents: 1299. This second observation matters if a client uses a decoder that rejects unknown properties. A contract that lists only the fields the client needs assumes the client can read a response with extra fields.
Price string. The serializer applies String(record.priceInCents). Pact reports that the value at $.price is a string where an integer was required. A direct call to the same provider reaches the storefront's Number.isInteger(body.price) check and fails to produce a price. Returning the stored integer directly fixes the mismatch. The repaired variant keeps the new badge and passes both interactions against the original pact.
Error code. The provider still returns 404 for a missing product, but the body contains "code": "NOT_FOUND". The contract points to $.code. The direct client call also reports an unhandled catalog response because its unavailable branch expects PRODUCT_NOT_FOUND. A screenshot of a generic error screen would give the catalog team less information than the expected and actual code in this report.
Wrong price. Set the serialized price to 1399 while the inventory record still says 1299. The contract passes and the storefront reads 1399 cents. An independent provider test that compares the response with the known inventory amount would catch the one-dollar error. Keep that business check alongside the contract test. Tightening the pact to today's exact price would also block legitimate price changes.
Use version pairs to make a release decision
Suppose Storefront 1.4 is deployed and Catalog 2.2 is the candidate with the quoted price. A useful build record names both revisions, identifies the exact pact file, and preserves the result of each interaction. The decision here is hold Catalog 2.2 for Storefront 1.4. The failing request is GET /products/P-17 in the existing-product state. Its response changed the JSON type of price. The catalog team can verify the corrected build against the very file that caught the change.
If the product really needs formatted price text, Catalog can introduce a separate displayPrice field alongside the numeric price. A storefront version that starts reading it creates its own contract. Verify that contract against the catalog version it will meet in the target environment. Before retiring the original field, check which deployed or supported consumer versions still require it. An untested version pair needs its own verification result.
Reserve shared-environment testing for questions that require the systems to operate together. For example, can the deployed storefront reach the correct catalog through its gateway and show the price for the selected product? The API integration testing checklist covers that workflow and its operational dependencies.
FAQ
An OpenAPI schema can describe the price type and the published error responses. This consumer test supplies evidence from one actual client. It runs the adapter that constructs the lookup and checks what the UI receives on each branch. Provider verification ties those expectations to a particular catalog build. The checks can share example data while answering different release questions.
Start with the client's behavior in each case. Suppose the storefront uses a fallback label when displayPrice is absent and would reject an explicit null. Give the adapter examples of both shapes in client tests. For a provider state in which the client requires a usable label, describe that value in the pact. An omitted response key in a Pact expectation allows the provider to send extra keys, so omission alone cannot establish that the actual response lacks the field.
You can still exercise your adapter against the examples and run agreed integration checks in the provider's sandbox. Record the sandbox version or observation date. Keep the consumer test result and the sandbox observation distinct in release evidence. Verification of a particular provider candidate requires access to that candidate or a verification result supplied by its provider.
For an order creation request, the contract can specify the submitted fields, response status, and returned order ID that the client uses. Test durable storage by reading the created record through an independent path in a provider test. If the client also makes a later lookup, describe the lookup as another interaction with its own starting state.