WireMock Python Client
The `wiremock` library provides a Python client for the WireMock Admin API, enabling programmatic control and configuration of WireMock standalone servers. It allows developers to define stub mappings, reset server state, and verify requests from Python tests or scripts. The current version is 2.7.0, with an active release cadence, often aligning with updates to the WireMock Java core.
Common errors
-
requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=8080): Max retries exceeded with url: /__admin/mappings (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x...>: Failed to establish a new connection: [Errno 111] Connection refused'))cause The WireMock Java server is not running or is not accessible at the specified host and port.fixStart your WireMock server before running the Python client code. Verify the `WIREMOCK_URL` environment variable or the `base_url` parameter in `WireMockClient` matches the running server's address. -
AttributeError: 'NoneType' object has no attribute 'build'
cause You've likely forgotten to return the result of a builder method in a fluent chain or one of the builder methods returned None unexpectedly.fixEnsure all `MappingBuilder` and `ResponseDefinitionBuilder` methods are properly chained and terminate with `.build()`. For example, `ResponseDefinitionBuilder.response().with_status(200).build()`. -
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
cause WireMock returned a non-JSON response (e.g., HTML error page, empty string) when the client expected JSON, or a stub was incorrectly configured to return malformed JSON.fixCheck the WireMock server logs for errors. Inspect the raw response from WireMock if possible (e.g., using `requests.get(...).text`). Correct your stub mapping's `with_body_as_json` or `with_header('Content-Type', 'application/json')` settings if the intent was JSON. -
ImportError: cannot import name 'WireMockClient' from 'wiremock.client' (path/to/venv/lib/python3.x/site-packages/wiremock/client/__init__.py)
cause This usually indicates a typo in the import statement, an old version of `wiremock` installed, or a corrupt virtual environment.fixEnsure the import statement is `from wiremock.client import WireMockClient`. If the error persists, check your `wiremock` version (`pip show wiremock`). If it's an older version (e.g., <2.0.0), upgrade it with `pip install --upgrade wiremock`.
Warnings
- breaking Version 2.0.0 introduced significant breaking changes, including renaming `AdminClient` to `WireMockClient` and a complete overhaul of the API for defining stub mappings.
- gotcha The `wiremock` Python client controls a WireMock server; it does not start or manage the server itself. You must have a WireMock Java server running independently (e.g., via JAR, Docker, or standalone). Failure to start the WireMock server will result in `ConnectionError`.
- gotcha When defining stub mappings, it's crucial to call `.build()` at the end of the `MappingBuilder` chain to finalize the mapping object before passing it to `client.create_mapping()`. Forgetting `.build()` will lead to incorrect object types or `AttributeError`.
- gotcha When running tests, stubs defined in previous tests can interfere with subsequent ones, leading to flaky results. It's good practice to clear WireMock's state between tests.
- gotcha The Python client's features and compatibility are tied to the version of the WireMock Java Admin API. New features in the Java server might not be immediately available or fully supported by older Python client versions.
Install
-
pip install wiremock
Imports
- WireMockClient
from wiremock import AdminClient
from wiremock.client import WireMockClient
- MappingBuilder
from wiremock.client import MappingBuilder
- ResponseDefinitionBuilder
from wiremock.client import ResponseDefinitionBuilder
Quickstart
import os
import requests
from wiremock.client import WireMockClient, MappingBuilder, ResponseDefinitionBuilder, HttpMethods
# The URL where your WireMock server is running. Make sure it's started!
# Example: `java -jar wiremock-standalone-2.35.0.jar --port 8080`
WIREMOCK_BASE_URL = os.environ.get('WIREMOCK_URL', 'http://localhost:8080')
client = WireMockClient(base_url=WIREMOCK_BASE_URL)
print(f"Connected to WireMock at {WIREMOCK_BASE_URL}")
# 1. Clear all existing stub mappings for a clean slate
client.reset_mappings()
print("All previous stub mappings cleared.")
# 2. Define a new stub mapping for a GET request to /hello
hello_stub = MappingBuilder.get(url_path='/hello') \
.will_return(
ResponseDefinitionBuilder.response() \
.with_status(200) \
.with_header('Content-Type', 'text/plain') \
.with_body('Hello from WireMock!')
) \
.build()
client.create_mapping(hello_stub)
print("Stub for GET /hello created.")
# 3. Verify the stub by making a request to the WireMock instance
try:
response = requests.get(f"{WIREMOCK_BASE_URL}/hello")
print(f"Request to /hello received status: {response.status_code}")
print(f"Response body: {response.text}")
assert response.status_code == 200
assert response.text == 'Hello from WireMock!'
print("Stub verified successfully!")
except requests.exceptions.ConnectionError as e:
print(f"Error: Could not connect to WireMock server at {WIREMOCK_BASE_URL}. Is it running?")
print(f"Details: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
# Optional: Clean up after verification
# client.reset_mappings()
# print("All stub mappings cleared again.")