The before code calls the provider API directly without guarantees the provider supports the expected response. The after code uses Pact to define a contract with expected requests and responses, tests the consumer against a mock provider, and enables the provider to verify the contract in CI, preventing integration errors.
### Before: No contract testing, direct API call without verification
import requests
def get_user_profile(user_id):
response = requests.get(f"http://provider/api/users/{user_id}")
return response.json()
### After: Consumer publishes Pact contract and verifies provider
from pact import Consumer, Provider
pact = Consumer('ConsumerService').has_pact_with(Provider('ProviderService'))
with pact:
expected = {'id': 1, 'name': 'Alice'}
pact.given('User 1 exists').upon_receiving('a request for user 1').with_request(
'get', '/api/users/1').will_respond_with(200, body=expected)
# Consumer test against mock provider
result = get_user_profile(1)
assert result == expected
# Provider CI runs pact.verify() to confirm contract compliance