Bird
Raised Fist0
Rest APIprogramming~10 mins

Contract testing in Rest API - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Contract testing
Define contract
↓
Provider implements API
↓
Consumer writes tests against contract
↓
Run contract tests
↓
Tests pass?
No→Fix provider or consumer
↓
Deploy with confidence
Contract testing ensures that the API provider and consumer agree on the API behavior by defining a contract and testing against it.
Execution Sample
Rest API
contract = {
  "GET /user": {"status": 200, "body": {"id": "int", "name": "string"}}
}

# Consumer test example
response = api_call("GET", "/user")
assert response.status == contract["GET /user"]["status"]
assert type(response.body["id"]) == int
assert type(response.body["name"]) == str
This code checks if the API response matches the contract for the GET /user endpoint.
Execution Table
StepActionEvaluationResult
1Call GET /user APISend request to providerResponse received with status 200 and body {"id": 123, "name": "Alice"}
2Check status coderesponse.status == 200True
3Check body id typetype(response.body["id"]) == intTrue
4Check body name typetype(response.body["name"]) == strTrue
5All contract checksAll TrueTest passes, contract fulfilled
💡 All contract conditions met, testing stops successfully
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
response.statusNone200200200200200
response.bodyNone{"id": 123, "name": "Alice"}{"id": 123, "name": "Alice"}{"id": 123, "name": "Alice"}{"id": 123, "name": "Alice"}{"id": 123, "name": "Alice"}
type(response.body["id"])Noneintintintintint
type(response.body["name"])Nonestrstrstrstrstr
Key Moments - 2 Insights
Why do we check the type of response fields instead of exact values?
Because the contract defines the expected data types, not exact values, so tests verify the structure and type to allow flexibility in actual data (see steps 3 and 4 in execution_table).
What happens if the status code does not match the contract?
The test fails immediately at step 2, indicating the provider does not meet the contract, so deployment should be stopped until fixed.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the response status after Step 1?
A200
B404
C500
DNone
💡 Hint
Check the 'After Step 1' column for response.status in variable_tracker.
At which step does the test confirm the response body has the correct 'name' type?
AStep 2
BStep 4
CStep 3
DStep 5
💡 Hint
Look at the 'Action' column in execution_table for type checks on 'name'.
If the API returned status 404 instead of 200, what would happen in the execution_table?
ATest would fail at Step 4
BTest would pass at Step 2
CTest would fail at Step 2
DTest would pass all steps
💡 Hint
Refer to Step 2 where status code equality is checked.
Concept Snapshot
Contract testing ensures API provider and consumer agree on API behavior.
Define a contract with expected endpoints, status codes, and data types.
Consumer tests call API and check response matches contract.
Tests fail if provider response differs, preventing integration errors.
This builds confidence before deployment.
Full Transcript
Contract testing is a way to make sure the API provider and consumer agree on how the API should behave. First, a contract is defined that lists the expected API endpoints, the status codes they should return, and the types of data in the response. The consumer then writes tests that call the API and check if the response matches this contract. For example, the test checks if the status code is 200 and if the response body fields have the correct data types. If any check fails, the test fails, signaling a problem. This helps catch issues early and ensures both sides work well together before deploying the API.

Practice

(1/5)
1. What is the main purpose of contract testing in REST APIs?
easy
A. To check the API's user interface design
B. To test the speed of the API response
C. To ensure two systems agree on the data they exchange
D. To monitor server hardware performance

Solution

  1. Step 1: Understand contract testing definition

    Contract testing checks if two systems agree on the data format and behavior during communication.
  2. Step 2: Compare options to definition

    Only To ensure two systems agree on the data they exchange matches this purpose; others relate to speed, UI, or hardware, which are unrelated.
  3. Final Answer:

    To ensure two systems agree on the data they exchange -> Option C
  4. Quick Check:

    Contract testing = data agreement [OK]
Hint: Contract testing checks data agreement between systems [OK]
Common Mistakes:
  • Confusing contract testing with performance testing
  • Thinking contract testing checks UI or hardware
  • Assuming contract testing is about security
2. Which of the following is the correct way to define a contract test for a REST API endpoint?
easy
A. Test the API's front-end layout on different browsers
B. Measure the time taken for the API to respond
C. Verify the API server's CPU usage during requests
D. Check if the API returns the expected status code and response body

Solution

  1. Step 1: Identify contract test elements

    Contract tests verify the API response matches the agreed format, including status codes and body content.
  2. Step 2: Match options to contract test definition

    Check if the API returns the expected status code and response body matches this exactly; others relate to performance, server metrics, or UI, which are not contract tests.
  3. Final Answer:

    Check if the API returns the expected status code and response body -> Option D
  4. Quick Check:

    Contract test = expected response check [OK]
Hint: Contract tests check expected status and response body [OK]
Common Mistakes:
  • Confusing contract tests with performance or UI tests
  • Ignoring response body content in contract tests
  • Testing server hardware instead of API contract
3. Given this contract test snippet in JavaScript using Pact: <pre>provider.addInteraction({ state: 'user exists', uponReceiving: 'a request for user data', withRequest: { method: 'GET', path: '/user/123' }, willRespondWith: { status: 200, body: { id: 123, name: 'Alice' } } }); What will happen if the provider returns status 404 instead of 200 during the test?
medium
A. The test will pass because the body matches the contract
B. The test will fail because the status code doesn't match the contract
C. The test will ignore the status code and only check the path
D. The test will pass if the response time is fast enough

Solution

  1. Step 1: Understand the contract test expectation

    The contract expects a 200 status code with a specific body when requesting '/user/123'.
  2. Step 2: Analyze the provider's actual response

    The provider returns 404, which does not match the expected 200 status code.
  3. Final Answer:

    The test will fail because the status code doesn't match the contract -> Option B
  4. Quick Check:

    Status mismatch causes test failure [OK]
Hint: Mismatch in status code causes contract test failure [OK]
Common Mistakes:
  • Assuming body match overrides status code mismatch
  • Ignoring status code in contract tests
  • Thinking response time affects contract test result
4. You wrote a contract test that expects a JSON response with a field email. The test fails because the provider returns emailAddress instead. What is the best way to fix this?
medium
A. Change the provider to return email as expected by the contract
B. Update the contract to expect emailAddress instead of email
C. Ignore the field mismatch and pass the test anyway
D. Remove the email field from the contract test

Solution

  1. Step 1: Identify contract responsibility

    The contract defines the expected data format; the provider must follow it.
  2. Step 2: Choose the correct fix

    Changing the provider to return email matches the contract, ensuring stable integration.
  3. Final Answer:

    Change the provider to return email as expected by the contract -> Option A
  4. Quick Check:

    Provider must match contract fields [OK]
Hint: Provider must match contract fields exactly [OK]
Common Mistakes:
  • Ignoring field name mismatches
  • Changing contract to fit provider without agreement
  • Removing important fields from contract
5. You have two microservices: Service A (consumer) and Service B (provider). Service A expects Service B's API to return a list of products with fields id, name, and price. You want to write a contract test that allows price to be optional (sometimes missing). Which approach best achieves this?
hard
A. Define the contract so price is optional using a matcher that allows missing fields
B. Require price always in the contract and fail if missing
C. Remove price from the contract entirely
D. Ignore the contract and test only after deployment

Solution

  1. Step 1: Understand optional fields in contract testing

    Contract tests can use matchers to allow fields to be optional or have flexible types.
  2. Step 2: Choose the approach that supports optional price

    Defining price as optional with a matcher allows the provider to omit it without failing the test.
  3. Final Answer:

    Define the contract so price is optional using a matcher that allows missing fields -> Option A
  4. Quick Check:

    Use matchers for optional fields in contracts [OK]
Hint: Use matchers to allow optional fields in contract tests [OK]
Common Mistakes:
  • Forcing optional fields to be always present
  • Removing important fields from contract
  • Skipping contract tests and testing only post-deployment
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard