WireMock Python Client

2.7.0 · active · verified Thu Apr 16

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

Warnings

Install

Imports

Quickstart

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.

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.")

view raw JSON →