--- title: MockServer Clients description: Control MockServer from Java, JavaScript, Python, Ruby, or the REST API to create expectations, verify requests, and retrieve recorded traffic. layout: page pageOrder: 2 section: 'General' subsection: true sitemap: priority: 0.8 changefreq: 'monthly' lastmod: 2026-05-12T00:00:00+00:00 ---

MockServer can be controlled in the following ways:

- REST API
- Java
- JavaScript (both browser API & Node.js module)
- Python (sync and async)
- Ruby

The following activities are supported:

- creating expectations
- verifying which requests have been received
- clearing or resetting recorded request, expectations or logs (selectively)

- Retrieving the following items:

  - recorded requests
  - recorded requests and responses
  - active expectations
  - recorded expectations
  - logs
- bind additional ports for MockServer to listen on

## REST API

The REST API is documented using Open API 3

## Java Client

The Java client has the following versions:

- org.mockserver.client.MockServerClient - makes HTTP requests to a remote MockServer instance
- org.mockserver.integration.ClientAndServer - starts a local MockServer instance and makes HTTP requests to it

## JavaScript Client

The JavaScript client has the following version:

- a browser based API file mockServerClient.js
- a Node.js npm module mockserver-client

To include the browser based client in an HTML page as follows:

    <script src="https://raw.githubusercontent.com/mock-server/mockserver-monorepo/master/mockserver-client-node/mockServerClient.js"></script>

## Python Client

The Python client provides both synchronous and asynchronous APIs:

- MockServerClient - synchronous client wrapping the async implementation
- AsyncMockServerClient - native async client using asyncio

Install via pip:

    pip install mockserver-client

The synchronous client supports context manager usage:

    from mockserver import MockServerClient, HttpRequest, HttpResponse

    with MockServerClient("localhost", 1080) as client:
        client.when(
            HttpRequest(path="/hello")
        ).respond(
            HttpResponse(status_code=200, body="world")
        )

The async client can be used with async with:

    from mockserver import AsyncMockServerClient, HttpRequest, HttpResponse

    async with AsyncMockServerClient("localhost", 1080) as client:
        await client.when(
            HttpRequest(path="/hello")
        ).respond(
            HttpResponse(status_code=200, body="world")
        )

Verification failures raise MockServerVerificationError (a subclass of both MockServerError and AssertionError). Connection failures raise MockServerConnectionError:

    from mockserver import MockServerClient, HttpRequest, VerificationTimes
    from mockserver.exceptions import MockServerVerificationError, MockServerConnectionError

    try:
        with MockServerClient("localhost", 1080) as client:
            client.verify(HttpRequest(path="/some/path"), times=VerificationTimes(at_least=1))
    except MockServerVerificationError as e:
        print(f"Verification failed: {e}")
    except MockServerConnectionError as e:
        print(f"Connection failed: {e}")

Requires Python >= 3.9.

## Ruby Client

The Ruby client provides a fluent builder DSL and WebSocket-based callback support:

- MockServer::Client - makes HTTP requests to a remote MockServer instance

Install via gem:

    gem install mockserver-client

The client supports a block form for automatic cleanup:

    require 'mockserver-client'

    MockServer::Client.new('localhost', 1080) do |client|
      client.when(
        MockServer::HttpRequest.new(path: '/hello')
      ).respond(
        MockServer::HttpResponse.new(body: 'world')
      )
    end

You can include MockServer to use shorter class names (e.g. HttpRequest instead of MockServer::HttpRequest). All accordion examples below use this pattern for brevity.

Verification failures raise MockServer::VerificationError. Connection failures raise MockServer::ConnectionError:

    require 'mockserver-client'
    include MockServer

    MockServer::Client.new('localhost', 1080) do |client|
      client.verify(HttpRequest.new(path: '/some/path'), times: VerificationTimes.at_least(1))
    rescue MockServer::VerificationError => e
      puts "Verification failed: #{e.message}"
    rescue MockServer::ConnectionError => e
      puts "Connection failed: #{e.message}"
    end

Requires Ruby >= 3.0.

    new MockServerClient("localhost", 1080)
        .when(
            request()
                .withMethod("GET")
                .withPath("/view/cart")
                .withCookies(
                    cookie("session", "4930456C-C718-476F-971F-CB8E047AB349")
                )
                .withQueryStringParameters(
                    param("cartId", "055CA455-1DF7-45BB-8535-4F83E7266092")
                )
        )
        .respond(
            response()
                .withBody("some_response_body")
        );

    new ClientAndServer(1080)
        .when(
            request()
                .withMethod("GET")
                .withPath("/view/cart")
                .withCookies(
                    cookie("session", "4930456C-C718-476F-971F-CB8E047AB349")
                )
                .withQueryStringParameters(
                    param("cartId", "055CA455-1DF7-45BB-8535-4F83E7266092")
                )
        )
        .respond(
            response()
                .withBody("some_response_body")
        );

    var mockServerClient = require('mockserver-client').mockServerClient;
    mockServerClient("localhost", 1080)
      .mockAnyResponse({
        "httpRequest": {
          "method": "GET",
          "path": "/view/cart",
          "queryStringParameters": {
            "cartId": ["055CA455-1DF7-45BB-8535-4F83E7266092"]
          },
          "cookies": {
            "session": "4930456C-C718-476F-971F-CB8E047AB349"
          }
        },
        "httpResponse": {
          "body": "some_response_body"
        }
      })
      .then(
        function () {
          console.log("expectation created");
        },
        function (error) {
          console.log(error);
        }
      );

    <script src="https://raw.githubusercontent.com/mock-server/mockserver-monorepo/master/mockserver-client-node/mockServerClient.js"></script>
    <script>
      mockServerClient("localhost", 1080)
        .mockAnyResponse({
          "httpRequest": {
            "method": "GET",
            "path": "/view/cart",
            "queryStringParameters": {
              "cartId": ["055CA455-1DF7-45BB-8535-4F83E7266092"]
            },
            "cookies": {
              "session": "4930456C-C718-476F-971F-CB8E047AB349"
            }
          },
          "httpResponse": {
            "body": "some_response_body"
          }
        })
        .then(
          function () {
            console.log("expectation created");
          },
          function (error) {
            console.log(error);
          }
        );
    </script>

    from mockserver import MockServerClient, HttpRequest, HttpResponse, KeyToMultiValue

    client = MockServerClient("localhost", 1080)
    client.when(
        HttpRequest(
            method="GET",
            path="/view/cart",
            cookies=[KeyToMultiValue(name="session", values=["4930456C-C718-476F-971F-CB8E047AB349"])],
            query_string_parameters=[KeyToMultiValue(name="cartId", values=["055CA455-1DF7-45BB-8535-4F83E7266092"])]
        )
    ).respond(
        HttpResponse(body="some_response_body")
    )

    require 'mockserver-client'
    include MockServer

    client = MockServer::Client.new('localhost', 1080)
    client.when(
      HttpRequest.new(
        method: 'GET',
        path: '/view/cart',
        cookies: [{ name: 'session', values: ['4930456C-C718-476F-971F-CB8E047AB349'] }],
        query_string_parameters: [{ name: 'cartId', values: ['055CA455-1DF7-45BB-8535-4F83E7266092'] }]
      )
    ).respond(
      HttpResponse.new(body: 'some_response_body')
    )

    curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
      "httpRequest" : {
        "method" : "GET",
        "path" : "/view/cart",
        "queryStringParameters" : {
          "cartId" : [ "055CA455-1DF7-45BB-8535-4F83E7266092" ]
        },
        "cookies" : {
          "session" : "4930456C-C718-476F-971F-CB8E047AB349"
        }
      },
      "httpResponse" : {
        "body" : "some_response_body"
      }
    }'

    new MockServerClient("localhost", 1080)
        .withSecure(true)
        .when(
            request()
                .withMethod("GET")
                .withPath("/view/cart")
                .withCookies(
                    cookie("session", "4930456C-C718-476F-971F-CB8E047AB349")
                )
                .withQueryStringParameters(
                    param("cartId", "055CA455-1DF7-45BB-8535-4F83E7266092")
                )
        )
        .respond(
            response()
                .withBody("some_response_body")
        );

    new ClientAndServer(1080)
        .withSecure(true)
        .when(
            request()
                .withMethod("GET")
                .withPath("/view/cart")
                .withCookies(
                    cookie("session", "4930456C-C718-476F-971F-CB8E047AB349")
                )
                .withQueryStringParameters(
                    param("cartId", "055CA455-1DF7-45BB-8535-4F83E7266092")
                )
        )
        .respond(
            response()
                .withBody("some_response_body")
        );

    var mockServerClient = require('mockserver-client').mockServerClient;
    mockServerClient("localhost", 1080, undefined, true)
      .mockAnyResponse({
        "httpRequest": {
          "method": "GET",
          "path": "/view/cart",
          "queryStringParameters": {
            "cartId": ["055CA455-1DF7-45BB-8535-4F83E7266092"]
          },
          "cookies": {
            "session": "4930456C-C718-476F-971F-CB8E047AB349"
          }
        },
        "httpResponse": {
          "body": "some_response_body"
        }
      })
      .then(
        function () {
          console.log("expectation created");
        },
        function (error) {
          console.log(error);
        }
      );

    from mockserver import MockServerClient, HttpRequest, HttpResponse, KeyToMultiValue

    client = MockServerClient("localhost", 1080, secure=True, tls_verify=False)
    client.when(
        HttpRequest(
            method="GET",
            path="/view/cart",
            cookies=[KeyToMultiValue(name="session", values=["4930456C-C718-476F-971F-CB8E047AB349"])],
            query_string_parameters=[KeyToMultiValue(name="cartId", values=["055CA455-1DF7-45BB-8535-4F83E7266092"])]
        )
    ).respond(
        HttpResponse(body="some_response_body")
    )

    require 'mockserver-client'
    include MockServer

    client = MockServer::Client.new('localhost', 1080, secure: true, tls_verify: false)
    client.when(
      HttpRequest.new(
        method: 'GET',
        path: '/view/cart',
        cookies: [{ name: 'session', values: ['4930456C-C718-476F-971F-CB8E047AB349'] }],
        query_string_parameters: [{ name: 'cartId', values: ['055CA455-1DF7-45BB-8535-4F83E7266092'] }]
      )
    ).respond(
      HttpResponse.new(body: 'some_response_body')
    )

    curl -v -k -X PUT "https://localhost:1080/mockserver/expectation" -d '{
      "httpRequest" : {
        "method" : "GET",
        "path" : "/view/cart",
        "queryStringParameters" : {
          "cartId" : [ "055CA455-1DF7-45BB-8535-4F83E7266092" ]
        },
        "cookies" : {
          "session" : "4930456C-C718-476F-971F-CB8E047AB349"
        }
      },
      "httpResponse" : {
        "body" : "some_response_body"
      }
    }'

    new MockServerClient("localhost", 1080)
        .verify(
            request()
                .withPath("/some/path"),
            VerificationTimes.atLeast(2)
        );

    new ClientAndServer(1080)
        .verify(
            request()
                .withPath("/some/path"),
            VerificationTimes.atLeast(2)
        );

    var mockServerClient = require('mockserver-client').mockServerClient;
    mockServerClient("localhost", 1080)
      .verify(
        {
          'path': '/some/path'
        }, 2, false)
      .then(
        function () {
          console.log("request found exactly 2 times");
        },
        function (error) {
          console.log(error);
        }
      );

    <script src="https://raw.githubusercontent.com/mock-server/mockserver-monorepo/master/mockserver-client-node/mockServerClient.js"></script>
    <script>
      mockServerClient("localhost", 1080)
        .verify(
          {
            'path': '/some/path'
          }, 2, false)
        .then(
          function () {
            console.log("request found exactly 2 times");
          },
          function (error) {
            console.log(error);
          }
        );
    </script>

    from mockserver import MockServerClient, HttpRequest, VerificationTimes

    client = MockServerClient("localhost", 1080)
    client.verify(
        HttpRequest(path="/some/path"),
        times=VerificationTimes(at_least=2)
    )

    require 'mockserver-client'
    include MockServer

    client = MockServer::Client.new('localhost', 1080)
    client.verify(
      HttpRequest.new(path: '/some/path'),
      times: VerificationTimes.at_least(2)
    )

    curl -v -X PUT "http://localhost:1080/mockserver/verify" -d '{
        "httpRequest": {
            "path": "/simple"
        },
        "times": {
            "atLeast": 2,
            "atMost": 2
        }
    }'

    new MockServerClient("localhost", 1080)
        .verify(
            request()
                .withPath("/some/path/one"),
            request()
                .withPath("/some/path/two"),
            request()
                .withPath("/some/path/three")
        );

    new ClientAndServer(1080)
        .verify(
            request()
                .withPath("/some/path/one"),
            request()
                .withPath("/some/path/two"),
            request()
                .withPath("/some/path/three")
        );

    var mockServerClient = require('mockserver-client').mockServerClient;
    mockServerClient("localhost", 1080)
      .verifySequence(
        {
          'path': '/some/path/one'
        },
        {
          'path': '/some/path/two'
        },
        {
          'path': '/some/path/three'
        }
      )
      .then(
        function () {
          console.log("request sequence found in the order specified");
        },
        function (error) {
          console.log(error);
        }
      );

    <script src="https://raw.githubusercontent.com/mock-server/mockserver-monorepo/master/mockserver-client-node/mockServerClient.js"></script>
    <script>
      mockServerClient("localhost", 1080)
        .verifySequence(
          {
            'path': '/some/path/one'
          },
          {
            'path': '/some/path/two'
          },
          {
            'path': '/some/path/three'
          }
        )
        .then(
          function () {
            console.log("request sequence found in the order specified");
          },
          function (error) {
            console.log(error);
          }
        );
    </script>

    from mockserver import MockServerClient, HttpRequest

    client = MockServerClient("localhost", 1080)
    client.verify_sequence(
        HttpRequest(path="/some/path/one"),
        HttpRequest(path="/some/path/two"),
        HttpRequest(path="/some/path/three")
    )

    require 'mockserver-client'
    include MockServer

    client = MockServer::Client.new('localhost', 1080)
    client.verify_sequence(
      HttpRequest.new(path: '/some/path/one'),
      HttpRequest.new(path: '/some/path/two'),
      HttpRequest.new(path: '/some/path/three')
    )

    curl -v -X PUT "http://localhost:1080/mockserver/verifySequence" -d '{
       "httpRequests":[
          {
             "path":"/some/path/one"
          },
          {
             "path":"/some/path/two"
          },
          {
             "path":"/some/path/three"
          }
       ]
    }'

    HttpRequest[] recordedRequests = new MockServerClient("localhost", 1080)
        .retrieveRecordedRequests(
            request()
                .withPath("/some/path")
                .withMethod("POST")
        );

    HttpRequest[] recordedRequests = new ClientAndServer(1080)
        .retrieveRecordedRequests(
            request()
                .withPath("/some/path")
                .withMethod("POST")
        );

    var mockServerClient = require('mockserver-client').mockServerClient;
    mockServerClient("localhost", 1080)
      .retrieveRecordedRequests({
        "path": "/some/path",
        "method": "POST"
      })
      .then(
        function (recordedRequests) {
          console.log(JSON.stringify(recordedRequests));
        },
        function (error) {
          console.log(error);
        }
      );

    <script src="https://raw.githubusercontent.com/mock-server/mockserver-monorepo/master/mockserver-client-node/mockServerClient.js"></script>
    <script>
      mockServerClient("localhost", 1080)
        .retrieveRecordedRequests({
          "path": "/some/path",
          "method": "POST"
        })
        .then(
          function (recordedRequests) {
            console.log(JSON.stringify(recordedRequests));
          },
          function (error) {
            console.log(error);
          }
        );
    </script>

    from mockserver import MockServerClient, HttpRequest

    client = MockServerClient("localhost", 1080)
    recorded_requests = client.retrieve_recorded_requests(
        HttpRequest(path="/some/path", method="POST")
    )

    require 'mockserver-client'
    include MockServer

    client = MockServer::Client.new('localhost', 1080)
    recorded_requests = client.retrieve_recorded_requests(
      request: HttpRequest.new(path: '/some/path', method: 'POST')
    )

    curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=REQUESTS" -d '{
        "path": "/some/path",
        "method": "POST"
    }'

    Expectation[] recordedExpectations = new MockServerClient("localhost", 1080)
        .retrieveRecordedExpectations(
            request()
                .withPath("/some/path")
                .withMethod("POST")
        );

    Expectation[] recordedExpectations = new ClientAndServer(1080)
        .retrieveRecordedExpectations(
            request()
                .withPath("/some/path")
                .withMethod("POST")
        );

    var mockServerClient = require('mockserver-client').mockServerClient;
    mockServerClient("localhost", 1080)
      .retrieveRecordedRequests({
        "path": "/some/path",
        "method": "POST"
      })
      .then(
        function (recordedRequests) {
          console.log(JSON.stringify(recordedRequests));
        },
        function (error) {
          console.log(error);
        }
      );

    <script src="https://raw.githubusercontent.com/mock-server/mockserver-monorepo/master/mockserver-client-node/mockServerClient.js"></script>
    <script>
      mockServerClient("localhost", 1080)
        .retrieveRecordedRequests({
          "path": "/some/path",
          "method": "POST"
        })
        .then(
          function (recordedRequests) {
            console.log(JSON.stringify(recordedRequests));
          },
          function (error) {
            console.log(error);
          }
        );
    </script>

    from mockserver import MockServerClient, HttpRequest

    client = MockServerClient("localhost", 1080)
    recorded_expectations = client.retrieve_recorded_expectations(
        HttpRequest(path="/some/path", method="POST")
    )

    require 'mockserver-client'
    include MockServer

    client = MockServer::Client.new('localhost', 1080)
    recorded_expectations = client.retrieve_recorded_expectations(
      request: HttpRequest.new(path: '/some/path', method: 'POST')
    )

    curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=REQUESTS" -d '{
        "path": "/some/path",
        "method": "POST"
    }'

    HttpRequest[] recordedRequests = new MockServerClient("localhost", 1080)
        .retrieveRecordedRequests(
            request()
                .withPath("/some/path")
                .withMethod("POST")
        );

    HttpRequest[] recordedRequests = new ClientAndServer(1080)
        .retrieveRecordedRequests(
            request()
                .withPath("/some/path")
                .withMethod("POST")
        );

    var mockServerClient = require('mockserver-client').mockServerClient;
    mockServerClient("localhost", 1080)
      .retrieveLogMessages({
        "path": "/some/path",
        "method": "POST"
      })
      .then(
        function (logMessages) {
          // logMessages is a String[]
          console.log(logMessages);
        },
        function (error) {
          console.log(error);
        }
      );

    <script src="https://raw.githubusercontent.com/mock-server/mockserver-monorepo/master/mockserver-client-node/mockServerClient.js"></script>
    <script>
      mockServerClient("localhost", 1080)
        .retrieveLogMessages({
          "path": "/some/path",
          "method": "POST"
        })
        .then(
          function (logMessages) {
            // logMessages is a String[]
            console.log(logMessages);
          },
          function (error) {
            console.log(error);
          }
        );
    </script>

    from mockserver import MockServerClient, HttpRequest

    client = MockServerClient("localhost", 1080)
    log_messages = client.retrieve_log_messages(
        HttpRequest(path="/some/path", method="POST")
    )

    require 'mockserver-client'
    include MockServer

    client = MockServer::Client.new('localhost', 1080)
    log_messages = client.retrieve_log_messages(
      request: HttpRequest.new(path: '/some/path', method: 'POST')
    )

    curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=LOGS" -d '{
        "path": "/some/path",
        "method": "POST"
    }'

    new MockServerClient("localhost", 1080).clear(
        request()
            .withPath("/some/path")
            .withMethod("POST")
    );

    new ClientAndServer(1080).clear(
        request()
            .withPath("/some/path")
            .withMethod("POST")
    );

    var mockServerClient = require('mockserver-client').mockServerClient;
    mockServerClient("localhost", 1080)
      .clear({
        'path': '/some/path'
      })
      .then(
        function () {
          console.log("cleared state that matches request matcher");
        },
        function (error) {
          console.log(error);
        }
      );

    <script src="https://raw.githubusercontent.com/mock-server/mockserver-monorepo/master/mockserver-client-node/mockServerClient.js"></script>
    <script>
      mockServerClient("localhost", 1080)
        .clear({
          'path': '/some/path'
        })
        .then(
          function () {
            console.log("cleared state that matches request matcher");
          },
          function (error) {
            console.log(error);
          }
        );
    </script>

    from mockserver import MockServerClient, HttpRequest

    client = MockServerClient("localhost", 1080)
    client.clear(HttpRequest(path="/some/path"))

    require 'mockserver-client'
    include MockServer

    client = MockServer::Client.new('localhost', 1080)
    client.clear(HttpRequest.new(path: '/some/path'))

    curl -v -X PUT "http://localhost:1080/mockserver/clear" -d '{
        "path": "/some/path"
    }'

    new MockServerClient("localhost", 1080).clear(
        request()
            .withPath("/some/path")
            .withMethod("POST"),
        ClearType.LOG
    );

    new ClientAndServer(1080).clear(
        request()
            .withPath("/some/path")
            .withMethod("POST"),
        ClearType.LOG
    );

    var mockServerClient = require('mockserver-client').mockServerClient;
    mockServerClient("localhost", 1080)
      .clear({
        'path': '/some/path'
      }, 'LOG')
      .then(
        function () {
          console.log("cleared state that matches request matcher");
        },
        function (error) {
          console.log(error);
        }
      );

    <script src="https://raw.githubusercontent.com/mock-server/mockserver-monorepo/master/mockserver-client-node/mockServerClient.js"></script>
    <script>
      mockServerClient("localhost", 1080)
        .clear({
          'path': '/some/path'
        }, 'LOG')
        .then(
          function () {
            console.log("cleared state that matches request matcher");
          },
          function (error) {
            console.log(error);
          }
        );
    </script>

    from mockserver import MockServerClient, HttpRequest

    client = MockServerClient("localhost", 1080)
    client.clear(HttpRequest(path="/some/path"), clear_type="LOG")

    require 'mockserver-client'
    include MockServer

    client = MockServer::Client.new('localhost', 1080)
    client.clear(HttpRequest.new(path: '/some/path'), type: 'LOG')

    curl -v -X PUT "http://localhost:1080/mockserver/clear?type=log" -d '{
        "path": "/some/path"
    }'

    new MockServerClient("localhost", 1080).reset();

    new ClientAndServer(1080).reset();

    var mockServerClient = require('mockserver-client').mockServerClient;
    mockServerClient("localhost", 1080)
      .reset()
      .then(
        function () {
          console.log("reset all state");
        },
        function (error) {
          console.log(error);
        }
      );

    <script src="https://raw.githubusercontent.com/mock-server/mockserver-monorepo/master/mockserver-client-node/mockServerClient.js"></script>
    <script>
      mockServerClient("localhost", 1080)
        .reset()
        .then(
          function () {
            console.log("reset all state");
          },
          function (error) {
            console.log(error);
          }
        );
    </script>

    from mockserver import MockServerClient

    client = MockServerClient("localhost", 1080)
    client.reset()

    require 'mockserver-client'

    client = MockServer::Client.new('localhost', 1080)
    client.reset

    curl -v -X PUT "http://localhost:1080/mockserver/reset

    List<Integer> boundPorts = new MockServerClient("localhost", 1080).bind(
                0
            );

    List<Integer> boundPorts = new ClientAndServer(1080).bind(
                0
            );

    from mockserver import MockServerClient

    client = MockServerClient("localhost", 1080)
    bound_ports = client.bind(0)

    require 'mockserver-client'

    client = MockServer::Client.new('localhost', 1080)
    bound_ports = client.bind(0)

    curl -v -X PUT "http://localhost:1080/mockserver/bind -d '{
        "ports": [
            0,
            0
        ]
    }'

    List<Integer> boundPorts = new MockServerClient("localhost", 1080).bind(
                1081, 1082
            );

    List<Integer> boundPorts = new ClientAndServer(1080).bind(
                1081, 1082
            );

    from mockserver import MockServerClient

    client = MockServerClient("localhost", 1080)
    bound_ports = client.bind(1081, 1082)

    require 'mockserver-client'

    client = MockServer::Client.new('localhost', 1080)
    bound_ports = client.bind(1081, 1082)

    curl -v -X PUT "http://localhost:1080/mockserver/bind -d '{
        "ports": [
            1081,
            1082
        ]
    }'