{"id":7866,"library":"wiremock","title":"WireMock Python Client","description":"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.","status":"active","version":"2.7.0","language":"en","source_language":"en","source_url":"https://github.com/wiremock/wiremock-python","tags":["testing","mocking","api","http","wiremock","integration-testing"],"install":[{"cmd":"pip install wiremock","lang":"bash","label":"Install stable version"}],"dependencies":[{"reason":"Used for making HTTP requests to the WireMock Admin API and for verifying stubs.","package":"requests","optional":false}],"imports":[{"note":"AdminClient was deprecated and removed in version 2.0.0; WireMockClient is the current entry point.","wrong":"from wiremock import AdminClient","symbol":"WireMockClient","correct":"from wiremock.client import WireMockClient"},{"symbol":"MappingBuilder","correct":"from wiremock.client import MappingBuilder"},{"symbol":"ResponseDefinitionBuilder","correct":"from wiremock.client import ResponseDefinitionBuilder"}],"quickstart":{"code":"import os\nimport requests\nfrom wiremock.client import WireMockClient, MappingBuilder, ResponseDefinitionBuilder, HttpMethods\n\n# The URL where your WireMock server is running. Make sure it's started!\n# Example: `java -jar wiremock-standalone-2.35.0.jar --port 8080`\nWIREMOCK_BASE_URL = os.environ.get('WIREMOCK_URL', 'http://localhost:8080')\nclient = WireMockClient(base_url=WIREMOCK_BASE_URL)\n\nprint(f\"Connected to WireMock at {WIREMOCK_BASE_URL}\")\n\n# 1. Clear all existing stub mappings for a clean slate\nclient.reset_mappings()\nprint(\"All previous stub mappings cleared.\")\n\n# 2. Define a new stub mapping for a GET request to /hello\nhello_stub = MappingBuilder.get(url_path='/hello') \\\n    .will_return(\n        ResponseDefinitionBuilder.response() \\\n            .with_status(200) \\\n            .with_header('Content-Type', 'text/plain') \\\n            .with_body('Hello from WireMock!')\n    ) \\\n    .build()\n\nclient.create_mapping(hello_stub)\nprint(\"Stub for GET /hello created.\")\n\n# 3. Verify the stub by making a request to the WireMock instance\ntry:\n    response = requests.get(f\"{WIREMOCK_BASE_URL}/hello\")\n    print(f\"Request to /hello received status: {response.status_code}\")\n    print(f\"Response body: {response.text}\")\n    assert response.status_code == 200\n    assert response.text == 'Hello from WireMock!'\n    print(\"Stub verified successfully!\")\nexcept requests.exceptions.ConnectionError as e:\n    print(f\"Error: Could not connect to WireMock server at {WIREMOCK_BASE_URL}. Is it running?\")\n    print(f\"Details: {e}\")\nexcept Exception as e:\n    print(f\"An unexpected error occurred: {e}\")\n\n# Optional: Clean up after verification\n# client.reset_mappings()\n# print(\"All stub mappings cleared again.\")","lang":"python","description":"This quickstart demonstrates how to connect to a WireMock server, clear existing stubs, define a new GET stub for `/hello`, and then verify it by making an HTTP request. Ensure a WireMock Java server is running independently before executing this code."},"warnings":[{"fix":"Migrate your code to use `WireMockClient` and the new fluent API for `MappingBuilder` and `ResponseDefinitionBuilder`. Refer to the official documentation for migration guides.","message":"Version 2.0.0 introduced significant breaking changes, including renaming `AdminClient` to `WireMockClient` and a complete overhaul of the API for defining stub mappings.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Before running your Python code, ensure your WireMock server is active and accessible at the specified `base_url`. Common ways to run it include `java -jar wiremock-standalone-2.35.0.jar --port 8080` or using a Docker container.","message":"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).\n\nFailure to start the WireMock server will result in `ConnectionError`.","severity":"gotcha","affected_versions":"All"},{"fix":"Always terminate your `MappingBuilder` and `ResponseDefinitionBuilder` fluent calls with `.build()`. For example: `MappingBuilder.get(...).will_return(ResponseDefinitionBuilder.response()...).build()`.","message":"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`.","severity":"gotcha","affected_versions":"All"},{"fix":"Use `client.reset_mappings()` to clear only stub mappings, or `client.reset_all()` to clear mappings, requests, and scenarios. This is often done in a `setUp` or `tearDown` method of your test runner.","message":"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.","severity":"gotcha","affected_versions":"All"},{"fix":"Keep both your WireMock Python client and WireMock Java server reasonably up-to-date. If encountering issues with new WireMock features, check the `wiremock-python` changelog and the WireMock Java documentation for compatibility notes.","message":"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.","severity":"gotcha","affected_versions":"All"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Start 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.","cause":"The WireMock Java server is not running or is not accessible at the specified host and port.","error":"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'))"},{"fix":"Ensure all `MappingBuilder` and `ResponseDefinitionBuilder` methods are properly chained and terminate with `.build()`. For example, `ResponseDefinitionBuilder.response().with_status(200).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.","error":"AttributeError: 'NoneType' object has no attribute 'build'"},{"fix":"Check 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.","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.","error":"json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)"},{"fix":"Ensure 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`.","cause":"This usually indicates a typo in the import statement, an old version of `wiremock` installed, or a corrupt virtual environment.","error":"ImportError: cannot import name 'WireMockClient' from 'wiremock.client' (path/to/venv/lib/python3.x/site-packages/wiremock/client/__init__.py)"}]}