Consumer Driven Contract Pact Mock in Python

Define and verify consumer-driven contracts using Pact's Consumer and Provider classes, mocking the provider to assert expected interactions.

Medium Python 3.9+ Aug 9, 2026 Microservices patterns 15 views 0 copies

Requires third-party packages — install first
pip install pact-python requests

Python code

21 lines
Python 3.9+
from pact import Consumer, Provider

pact = Consumer('OrderService').has_pact_with(Provider('InventoryService'))

@Pact.verify()
class TestInventoryContract:
    def test_get_inventory(self):
        expected = {"item": "widget", "quantity": 100}
        (pact
         .given('inventory exists for widget')
         .upon_receiving('a request for widget inventory')
         .with_request('get', '/inventory/widget')
         .will_respond_with(200, body=expected))

        with pact:
            result = requests.get('http://localhost:8080/inventory/widget').json()
            assert result == expected

if __name__ == '__main__':
    import doctest
    doctest.testmod()

Output

stdout
1 items passed all tests:

1 tests in 1 items.
1 passed and 0 failed.
Test passed.

How it works

The Pact consumer test defines an expected interaction with the provider by specifiying a request and response. The given clause sets up provider state, and upon_receiving describes the intent. Inside the with pact: block, the mock provider runs and the real HTTP call is made against it. If the request and response match the defined contract, the test passes. This verifies that the consumer's expectations align with the provider's contract before deployment.

Common mistakes

  • Forgetting to install pact-python and requests, causing ImportError.
  • Not running the pact broker to share contracts with the provider team.
  • Hardcoding the provider URL instead of using the mock server's dynamic port.
  • Missing provider state setup (given) when the provider requires specific data.

Variations

  1. Use `pact.verify()` on a test class to automatically verify all tests.
  2. Export the generated pact file to a broker for provider verification.
  3. Use `pact._version` and `pact._pact_dir` to control output locations.

Real-world use cases

  • Verifying that a frontend service's API calls match the backend's actual responses before deploying.
  • Enforcing API compatibility between multiple microservices in a CI pipeline.
  • Testing that a consumer handles new fields in a provider response without breaking.

Sponsored

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Microservices patterns

Related tutorials and quizzes for this topic.