Record & Replay
Record & replay means proxying live HTTP(S) traffic through MockServer once, capturing the real requests and the responses the upstream returned, then serving those captured responses back as mock expectations — so the same interactions can be replayed on demand with the real dependency switched off.
This turns a one-off recording into a reusable, deterministic test fixture. Unlike re-recording against the live service on every run, a replayed recording is fast, offline, repeatable, and immune to upstream outages, rate limits, or drifting data — which is exactly what you want for CI and for reproducing a specific scenario. The steps below cover recording the traffic and retrieving it as expectations ready to replay.
To analyse the requests that a system makes the proxy can be used to record all requests and their corresponding responses.
All requests and responses can be retrieved as expectations (called recorded expectations) in Java code or JSON. This allows an easy way to replay a recording from the proxy.
Unlike conventional record-replay approaches typically provided by other proxies, MockServer allows easy editing of the recorded requests because the recording is provided as Java code or JSON. This ensures that if minor changes are made to an API the recording can easily be modified and no re-recording required avoiding the need to update test assertions.
One-Command Record & Replay
The fastest way to record from a real upstream is a single retrieve call with the optional forwardUnmatchedTo parameter. It arms record-and-forward in one step — any request that does not match an existing expectation is forwarded to the upstream and recorded — so you no longer need to separately configure proxyRemoteHost / proxyRemotePort and attemptToProxyIfNoMatchingExpectation before you start:
# 1. point MockServer at the upstream (this call arms recording for the session)
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=RECORDED_EXPECTATIONS&format=java&forwardUnmatchedTo=https://api.example.com"
# 2. run your application / tests against http://localhost:1080 so real traffic is recorded
# 3. retrieve the recording as ready-to-use code (or JSON) — in any supported format
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=RECORDED_EXPECTATIONS&format=java"
The forwardUnmatchedTo value accepts a bare host (api.example.com), a host and port (api.example.com:9090), or a full URL (http://api.example.com:9090 / https://api.example.com, which default to port 80/443). The upstream host is validated against the same private-network / cloud-metadata SSRF protection as the normal forward and replay paths before any connection is made — a blocked upstream returns 403 and a malformed value returns 400, in both cases leaving the configuration untouched.
Recording is traffic-driven: the first call only arms recording, it does not generate any traffic itself. Combine with the deduplicateRecordedExpectations property to collapse structurally-identical calls (e.g. /users/1 and /users/2) into a single templatized /users/{id} expectation in the retrieved output.
By default only id-like path segments are templatized. Enable the templatizeRecordedValues property (in addition to deduplicateRecordedExpectations) to also generalize volatile-looking query parameter, header and JSON body values — UUIDs, long ids, ISO-8601 / epoch-millis timestamps, JWTs and long opaque tokens — into regex matchers, so the recorded expectation matches future requests instead of being pinned to one captured value. It is conservative: stable values (short strings, words, booleans, small numbers such as a page size or status code) are kept verbatim. Both properties are off by default, so recorded output is unchanged unless you opt in.
Consolidate a Recording Into Reusable Mocks
Without any options, a recording is a verbatim one-to-one dump: recording 50 hits to GET /users/123 gives you 50 identical single-use expectations. Add consolidate=true to the retrieve call to collapse a recording into a compact, reusable mock set in one step — without having to set any server property first:
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=RECORDED_EXPECTATIONS&consolidate=true"
With consolidate=true MockServer groups recorded calls by request shape and, for each shape, returns a single unlimited-use expectation (so it keeps matching instead of expiring after one call). Calls that differ only in an id path segment (/users/123, /users/456) collapse into one /users/{id} expectation; volatile request headers (Authorization, User-Agent, tracing headers, …) are dropped from the matcher; and when the same request returned different responses over time, those responses are attached as a sequence (the first call gets the first response, the next call the second, and so on). Add parameterize=true as well to also generalize volatile query-parameter, header and JSON-body values (UUIDs, timestamps, tokens) into matchers.
Recording with no query parameter is unchanged, so existing scripts keep working.
Promote a Recording to Active Mocks
To turn a recording directly into active mocks on the running server — consolidated, parameterized, secret-redacted and ready to serve — call the promote endpoint after recording:
# promote all recorded traffic to active mocks
curl -v -X PUT "http://localhost:1080/mockserver/recordings/promote"
# or promote only traffic matching a request filter (JSON body)
curl -v -X PUT "http://localhost:1080/mockserver/recordings/promote" \
-d '{ "path": "/users/.*" }'
The promote endpoint retrieves the matching recorded traffic, redacts credentials (on by default), consolidates and parameterizes it (both on by default — add ?consolidate=false or ?parameterize=false to turn either off), then activates the resulting unlimited-use expectations and returns them as JSON with a 201 Created status. After that you can switch the real dependency off and serve the recording back with no further configuration.
Export Recorded Expectations as Client Code
Recorded (and active) expectations can be exported as ready-to-paste client code so you can drop a recording straight into a test. Use the retrieve API with type=RECORDED_EXPECTATIONS (or type=ACTIVE_EXPECTATIONS) and a code format:
- format=java — MockServer Java client builder DSL
- format=javascript — Node.js client calls (
mockServerClient(...).mockAnyResponse(…)) - format=python — Python client calls (
client.upsert(Expectation.from_dict(…))) - format=go — Go client calls (
client.Upsert(…)) - format=csharp — C# client calls (
client.Upsert(…)) - format=ruby — Ruby client calls (
client.upsert(…)) - format=rust — Rust client calls (
client.upsert(…)) - format=php — PHP client calls (
$client->upsertExpectation(…)) - format=json — round-trippable MockServer JSON
One client call is generated per expectation. For example, to export the recorded expectations as JavaScript:
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=RECORDED_EXPECTATIONS&format=javascript"
or as Python:
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=RECORDED_EXPECTATIONS&format=python"
or as Go, C#, Ruby, Rust or PHP — e.g. Go:
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=RECORDED_EXPECTATIONS&format=go"
Every language's output embeds the expectation's JSON inside a real client call, so it is correct for the published client packages (mockserver-client for Node.js, mockserver for Python, mockserver-client-go for Go, MockServer.Client for C#, the mockserver-client gem for Ruby, the mockserver-client crate for Rust, and mock-server/mockserver-client for PHP) and round-trips back into MockServer. In the dashboard, all of these formats are available under Library → Export, each with a Copy as code button; the same Export tab can also generate verification code from the recorded requests in Java, JavaScript, Python, Go, C#, Ruby and Rust.
HAR Export
Recorded requests and responses can be exported as a HAR (HTTP Archive) 1.2 file, which is a standard format supported by browser DevTools and other HTTP analysis tools.
To export as HAR, use the retrieve API with type=REQUEST_RESPONSES and format=HAR:
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=REQUEST_RESPONSES&format=HAR"
Automatic Persistence of Recorded Expectations
By default, recorded proxy traffic is only held in memory and lost when MockServer restarts. To automatically persist recorded expectations to a JSON file, configure the following properties:
- persistRecordedExpectations - set to true to enable automatic persistence of recorded expectations
- persistedRecordedExpectationsPath - file path for saving the recorded expectations (default: persistedRecordedExpectations.json)
The file is updated whenever a new request is forwarded through the proxy. The saved file can be loaded back into MockServer using the initializationJsonPath property to replay the recorded traffic.
Retrieving Recorded Expectations
All proxied requests including those proxied using a forward actions are recorded containing the request received and response returned.
It is possible to retrieve the recorded requests and responses as expectations so that they can be easily used as expectations to simulation a system.
Expectations are returned in the order they have been recorded. The expectations are returned can be filter using a request matcher.
Expectation[] recordedExpectations = new MockServerClient("localhost", 1080)
.retrieveRecordedExpectations(
request()
);
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080)
.retrieveRecordedExpectations({})
.then(
function (recordedExpectations) {
console.log(JSON.stringify(recordedExpectations));
},
function (error) {
console.log(error);
}
);
See REST API for full JSON specification
from mockserver.client import MockServerClient
client = MockServerClient("localhost", 1080)
recorded_expectations = client.retrieve_recorded_expectations()
require 'mockserver-client'
client = MockServer::Client.new('localhost', 1080)
recorded_expectations = client.retrieve_recorded_expectations
import mockserver "github.com/mock-server/mockserver-monorepo/mockserver-client-go/v7"
client := mockserver.New("localhost", 1080)
recordedExpectations, err := client.RetrieveRecordedExpectations(nil)
using MockServer.Client;
using var client = new MockServerClient("localhost", 1080);
var recordedExpectations = client.RetrieveRecordedExpectations();
use mockserver_client::ClientBuilder;
let client = ClientBuilder::new("localhost", 1080).build().unwrap();
let recorded_expectations = client.retrieve_recorded_expectations(None).unwrap();
use MockServer\MockServerClient;
$client = new MockServerClient('localhost', 1080);
$recordedExpectations = $client->retrieveRecordedExpectations();
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=RECORDED_EXPECTATIONS"
See REST API for full JSON specification
Expectation[] recordedExpectations = new MockServerClient("localhost", 1080)
.retrieveRecordedExpectations(
request()
.withPath("/some/path")
.withMethod("POST")
);
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).retrieveRecordedExpectations({
"path": "/some/path",
"method": "POST"
}).then(
function (recordedExpectations) {
console.log(JSON.stringify(recordedExpectations));
},
function (error) {
console.log(error);
}
);
See REST API for full JSON specification
from mockserver.client import MockServerClient
from mockserver.models import HttpRequest
client = MockServerClient("localhost", 1080)
recorded_expectations = client.retrieve_recorded_expectations(
HttpRequest(path="/some/path", method="POST")
)
require 'mockserver-client'
client = MockServer::Client.new('localhost', 1080)
recorded_expectations = client.retrieve_recorded_expectations(
request: MockServer::HttpRequest.new(path: '/some/path', method: 'POST')
)
import mockserver "github.com/mock-server/mockserver-monorepo/mockserver-client-go/v7"
client := mockserver.New("localhost", 1080)
recordedExpectations, err := client.RetrieveRecordedExpectations(
mockserver.Request().Path("/some/path").Method("POST"),
)
using MockServer.Client;
using MockServer.Client.Models;
using var client = new MockServerClient("localhost", 1080);
var recordedExpectations = client.RetrieveRecordedExpectations(
HttpRequest.Request().WithPath("/some/path").WithMethod("POST")
);
use mockserver_client::{ClientBuilder, HttpRequest};
let client = ClientBuilder::new("localhost", 1080).build().unwrap();
let filter = HttpRequest::new().path("/some/path").method("POST");
let recorded_expectations = client.retrieve_recorded_expectations(Some(&filter)).unwrap();
use MockServer\MockServerClient;
use MockServer\HttpRequest;
$client = new MockServerClient('localhost', 1080);
$recordedExpectations = $client->retrieveRecordedExpectations(
HttpRequest::request()->path('/some/path')->method('POST')
);
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=RECORDED_EXPECTATIONS" -d '{
"path": "/some/path",
"method": "POST"
}'
See REST API for full JSON specification
String recordedExpectations = new MockServerClient("localhost", 1080)
.retrieveRecordedExpectations(
request()
.withPath("/some/path")
.withMethod("POST"),
Format.JAVA
);
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=RECORDED_EXPECTATIONS&format=JAVA" -d '{
"path": "/some/path"
}'
See REST API for full JSON specification
String recordedExpectations = new MockServerClient("localhost", 1080)
.retrieveRecordedExpectations(
request()
.withPath("/some/path")
.withMethod("POST"),
Format.JAVASCRIPT
);
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=RECORDED_EXPECTATIONS&format=JAVASCRIPT" -d '{
"path": "/some/path"
}'
Returns copy-paste-ready code for the Node.js (mockserver-client) client, embedding each expectation's JSON in a mockAnyResponse(...) call. Also available for type=ACTIVE_EXPECTATIONS.
See REST API for full JSON specification
String recordedExpectations = new MockServerClient("localhost", 1080)
.retrieveRecordedExpectations(
request()
.withPath("/some/path")
.withMethod("POST"),
Format.PYTHON
);
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=RECORDED_EXPECTATIONS&format=PYTHON" -d '{
"path": "/some/path"
}'
Returns copy-paste-ready code for the Python (mockserver) client, embedding each expectation's JSON in a client.upsert(...) call. Also available for type=ACTIVE_EXPECTATIONS.
See REST API for full JSON specification
String recordedExpectations = new MockServerClient("localhost", 1080)
.retrieveRecordedExpectations(
request()
.withPath("/some/path")
.withMethod("POST"),
Format.GO
);
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=RECORDED_EXPECTATIONS&format=GO" -d '{
"path": "/some/path"
}'
Returns copy-paste-ready code for the Go (mockserver-client-go) client, embedding each expectation's JSON in a client.Upsert(...) call. Also available for type=ACTIVE_EXPECTATIONS.
See REST API for full JSON specification
String recordedExpectations = new MockServerClient("localhost", 1080)
.retrieveRecordedExpectations(
request()
.withPath("/some/path")
.withMethod("POST"),
Format.CSHARP
);
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=RECORDED_EXPECTATIONS&format=CSHARP" -d '{
"path": "/some/path"
}'
Returns copy-paste-ready code for the C# (MockServer.Client) client, embedding each expectation's JSON in a client.Upsert(...) call. Also available for type=ACTIVE_EXPECTATIONS.
See REST API for full JSON specification
String recordedExpectations = new MockServerClient("localhost", 1080)
.retrieveRecordedExpectations(
request()
.withPath("/some/path")
.withMethod("POST"),
Format.RUBY
);
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=RECORDED_EXPECTATIONS&format=RUBY" -d '{
"path": "/some/path"
}'
Returns copy-paste-ready code for the Ruby (mockserver-client) client, embedding each expectation's JSON in a client.upsert(...) call. Also available for type=ACTIVE_EXPECTATIONS.
See REST API for full JSON specification
String recordedExpectations = new MockServerClient("localhost", 1080)
.retrieveRecordedExpectations(
request()
.withPath("/some/path")
.withMethod("POST"),
Format.RUST
);
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=RECORDED_EXPECTATIONS&format=RUST" -d '{
"path": "/some/path"
}'
Returns copy-paste-ready code for the Rust (mockserver-client) crate, embedding each expectation's JSON in a client.upsert(...) call. Also available for type=ACTIVE_EXPECTATIONS.
See REST API for full JSON specification
String recordedExpectations = new MockServerClient("localhost", 1080)
.retrieveRecordedExpectations(
request()
.withPath("/some/path")
.withMethod("POST"),
Format.PHP
);
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=RECORDED_EXPECTATIONS&format=PHP" -d '{
"path": "/some/path"
}'
Returns copy-paste-ready code for the PHP (mock-server/mockserver-client) client, embedding each expectation's JSON in a $client->upsertExpectation(...) call. Also available for type=ACTIVE_EXPECTATIONS.
See REST API for full JSON specification
String recordedExpectations = new MockServerClient("localhost", 1080)
.retrieveRecordedExpectations(
request()
.withPath("/some/path")
.withMethod("POST"),
Format.JSON
);
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).retrieveRecordedExpectations({
"path": "/some/path",
"method": "POST"
}).then(
function (recordedExpectations) {
console.log(JSON.stringify(recordedExpectations));
},
function (error) {
console.log(error);
}
);
See REST API for full JSON specification
from mockserver.client import MockServerClient
from mockserver.models import HttpRequest
client = MockServerClient("localhost", 1080)
# retrieve returns JSON by default
recorded_expectations = client.retrieve_recorded_expectations(
HttpRequest(path="/some/path", method="POST")
)
require 'mockserver-client'
client = MockServer::Client.new('localhost', 1080)
# retrieve returns JSON by default
recorded_expectations = client.retrieve_recorded_expectations(
request: MockServer::HttpRequest.new(path: '/some/path', method: 'POST')
)
import mockserver "github.com/mock-server/mockserver-monorepo/mockserver-client-go/v7"
client := mockserver.New("localhost", 1080)
// RetrieveRecordedExpectations returns JSON-parsed expectations
recordedExpectations, err := client.RetrieveRecordedExpectations(
mockserver.Request().Path("/some/path").Method("POST"),
)
using MockServer.Client;
using MockServer.Client.Models;
using var client = new MockServerClient("localhost", 1080);
// RetrieveRecordedExpectations returns JSON-parsed expectations
var recordedExpectations = client.RetrieveRecordedExpectations(
HttpRequest.Request().WithPath("/some/path").WithMethod("POST")
);
use mockserver_client::{ClientBuilder, HttpRequest};
let client = ClientBuilder::new("localhost", 1080).build().unwrap();
let filter = HttpRequest::new().path("/some/path").method("POST");
// retrieve_recorded_expectations returns JSON-parsed expectations
let recorded_expectations = client.retrieve_recorded_expectations(Some(&filter)).unwrap();
use MockServer\MockServerClient;
use MockServer\HttpRequest;
$client = new MockServerClient('localhost', 1080);
// retrieveRecordedExpectations returns JSON-parsed expectations
$recordedExpectations = $client->retrieveRecordedExpectations(
HttpRequest::request()->path('/some/path')->method('POST')
);
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=RECORDED_EXPECTATIONS&format=JSON" -d '{
"path": "/some/path"
}'
See REST API for full JSON specification
Retrieving Recorded Requests
All requests the MockServer receives are recorded, including both proxied requests and requests that have matched an expectation.
It is possible to retrieve the recorded requests, as show below in the code examples.
Requests are returned in the order they have been recorded. Which requests are returned can be filter using a request matcher.
HttpRequest[] recordedRequests = new MockServerClient("localhost", 1080)
.retrieveRecordedRequests(
request()
);
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080)
.retrieveRecordedRequests({})
.then(
function (recordedRequests) {
console.log(JSON.stringify(recordedRequests));
},
function (error) {
console.log(error);
}
);
See REST API for full JSON specification
from mockserver.client import MockServerClient
client = MockServerClient("localhost", 1080)
recorded_requests = client.retrieve_recorded_requests()
require 'mockserver-client'
client = MockServer::Client.new('localhost', 1080)
recorded_requests = client.retrieve_recorded_requests
import mockserver "github.com/mock-server/mockserver-monorepo/mockserver-client-go/v7"
client := mockserver.New("localhost", 1080)
recordedRequests, err := client.RetrieveRecordedRequests(nil)
using MockServer.Client;
using var client = new MockServerClient("localhost", 1080);
var recordedRequests = client.RetrieveRecordedRequests();
use mockserver_client::ClientBuilder;
let client = ClientBuilder::new("localhost", 1080).build().unwrap();
let recorded_requests = client.retrieve_recorded_requests(None).unwrap();
use MockServer\MockServerClient;
$client = new MockServerClient('localhost', 1080);
$recordedRequests = $client->retrieveRecordedRequests();
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=REQUESTS"
See REST API for full JSON specification
HttpRequest[] recordedRequests = new MockServerClient("localhost", 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);
}
);
See REST API for full JSON specification
from mockserver.client import MockServerClient
from mockserver.models import HttpRequest
client = MockServerClient("localhost", 1080)
recorded_requests = client.retrieve_recorded_requests(
HttpRequest(path="/some/path", method="POST")
)
require 'mockserver-client'
client = MockServer::Client.new('localhost', 1080)
recorded_requests = client.retrieve_recorded_requests(
request: MockServer::HttpRequest.new(path: '/some/path', method: 'POST')
)
import mockserver "github.com/mock-server/mockserver-monorepo/mockserver-client-go/v7"
client := mockserver.New("localhost", 1080)
recordedRequests, err := client.RetrieveRecordedRequests(
mockserver.Request().Path("/some/path").Method("POST"),
)
using MockServer.Client;
using MockServer.Client.Models;
using var client = new MockServerClient("localhost", 1080);
var recordedRequests = client.RetrieveRecordedRequests(
HttpRequest.Request().WithPath("/some/path").WithMethod("POST")
);
use mockserver_client::{ClientBuilder, HttpRequest};
let client = ClientBuilder::new("localhost", 1080).build().unwrap();
let filter = HttpRequest::new().path("/some/path").method("POST");
let recorded_requests = client.retrieve_recorded_requests(Some(&filter)).unwrap();
use MockServer\MockServerClient;
use MockServer\HttpRequest;
$client = new MockServerClient('localhost', 1080);
$recordedRequests = $client->retrieveRecordedRequests(
HttpRequest::request()->path('/some/path')->method('POST')
);
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=REQUESTS" -d '{
"path": "/some/path",
"method": "POST"
}'
See REST API for full JSON specification
String recordedRequests = new MockServerClient("localhost", 1080)
.retrieveRecordedRequests(
request()
.withPath("/some/path")
.withMethod("POST"),
Format.JAVA
);
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=REQUESTS&format=JAVA" -d '{
"path": "/some/path"
}'
See REST API for full JSON specification
String recordedRequests = new MockServerClient("localhost", 1080)
.retrieveRecordedRequests(
request()
.withPath("/some/path")
.withMethod("POST"),
Format.JSON
);
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);
}
);
See REST API for full JSON specification
from mockserver.client import MockServerClient
from mockserver.models import HttpRequest
client = MockServerClient("localhost", 1080)
# retrieve returns JSON by default
recorded_requests = client.retrieve_recorded_requests(
HttpRequest(path="/some/path", method="POST")
)
require 'mockserver-client'
client = MockServer::Client.new('localhost', 1080)
# retrieve returns JSON by default
recorded_requests = client.retrieve_recorded_requests(
request: MockServer::HttpRequest.new(path: '/some/path', method: 'POST')
)
import mockserver "github.com/mock-server/mockserver-monorepo/mockserver-client-go/v7"
client := mockserver.New("localhost", 1080)
// RetrieveRecordedRequests returns JSON-parsed requests
recordedRequests, err := client.RetrieveRecordedRequests(
mockserver.Request().Path("/some/path").Method("POST"),
)
using MockServer.Client;
using MockServer.Client.Models;
using var client = new MockServerClient("localhost", 1080);
// RetrieveRecordedRequests returns JSON-parsed requests
var recordedRequests = client.RetrieveRecordedRequests(
HttpRequest.Request().WithPath("/some/path").WithMethod("POST")
);
use mockserver_client::{ClientBuilder, HttpRequest};
let client = ClientBuilder::new("localhost", 1080).build().unwrap();
let filter = HttpRequest::new().path("/some/path").method("POST");
// retrieve_recorded_requests returns JSON-parsed requests
let recorded_requests = client.retrieve_recorded_requests(Some(&filter)).unwrap();
use MockServer\MockServerClient;
use MockServer\HttpRequest;
$client = new MockServerClient('localhost', 1080);
// retrieveRecordedRequests returns JSON-parsed requests
$recordedRequests = $client->retrieveRecordedRequests(
HttpRequest::request()->path('/some/path')->method('POST')
);
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=REQUESTS&format=JSON" -d '{
"path": "/some/path"
}'
See REST API for full JSON specification
Retrieve Recorded Requests & Responses
All requests the MockServer receives are recorded, including both proxied requests and requests that have matched an expectation.
It is possible to retrieve the recorded requests and their responses, as show below in the code examples.
Requests and responses are returned in the order they have been recorded. Which requests are returned can be filter using a request matcher.
HttpRequestAndHttpResponse[] httpRequestAndHttpResponse = new MockServerClient("localhost", 1080)
.retrieveRecordedRequestsAndResponses(
request()
);
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080)
.retrieveRecordedRequestsAndResponses({})
.then(
function (recordedRequestsAndResponses) {
console.log(JSON.stringify(recordedRequestsAndResponses));
},
function (error) {
console.log(error);
}
);
See REST API for full JSON specification
from mockserver.client import MockServerClient
client = MockServerClient("localhost", 1080)
recorded = client.retrieve_recorded_requests_and_responses()
require 'mockserver-client'
client = MockServer::Client.new('localhost', 1080)
recorded = client.retrieve_recorded_requests_and_responses
import mockserver "github.com/mock-server/mockserver-monorepo/mockserver-client-go/v7"
client := mockserver.New("localhost", 1080)
// use the raw Retrieve method for request/response pairs
data, err := client.Retrieve(nil, mockserver.RetrieveRequestResponses, mockserver.FormatJSON)
using MockServer.Client;
using var client = new MockServerClient("localhost", 1080);
var recorded = client.RetrieveRecordedRequests();
// note: .NET client retrieves requests; for full request/response pairs use the REST API
use mockserver_client::ClientBuilder;
let client = ClientBuilder::new("localhost", 1080).build().unwrap();
let recorded = client.retrieve_request_responses(None).unwrap();
// no built-in request/response pair retrieve method; use curl
$ch = curl_init('http://localhost:1080/mockserver/retrieve?type=REQUEST_RESPONSES');
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => 'PUT',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/json; charset=utf-8'],
]);
$recorded = json_decode(curl_exec($ch), true);
curl_close($ch);
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=REQUEST_RESPONSES"
See REST API for full JSON specification
HttpRequestAndHttpResponse[] httpRequestAndHttpResponse = new MockServerClient("localhost", 1080)
.retrieveRecordedRequestsAndResponses(
request()
.withPath("/some/path")
.withMethod("POST")
);
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).retrieveRecordedRequestsAndResponses({
"path": "/some/path",
"method": "POST"
}).then(
function (recordedRequestsAndResponses) {
console.log(JSON.stringify(recordedRequestsAndResponses));
},
function (error) {
console.log(error);
}
);
See REST API for full JSON specification
from mockserver.client import MockServerClient
from mockserver.models import HttpRequest
client = MockServerClient("localhost", 1080)
recorded = client.retrieve_recorded_requests_and_responses(
HttpRequest(path="/some/path", method="POST")
)
require 'mockserver-client'
client = MockServer::Client.new('localhost', 1080)
recorded = client.retrieve_recorded_requests_and_responses(
request: MockServer::HttpRequest.new(path: '/some/path', method: 'POST')
)
import mockserver "github.com/mock-server/mockserver-monorepo/mockserver-client-go/v7"
client := mockserver.New("localhost", 1080)
data, err := client.Retrieve(
mockserver.Request().Path("/some/path").Method("POST"),
mockserver.RetrieveRequestResponses,
mockserver.FormatJSON,
)
using System.Net.Http;
using System.Text;
using var httpClient = new HttpClient();
var json = @"{
""path"": ""/some/path"",
""method"": ""POST""
}";
var response = await httpClient.PutAsync(
"http://localhost:1080/mockserver/retrieve?type=REQUEST_RESPONSES",
new StringContent(json, Encoding.UTF8, "application/json")
);
var recorded = await response.Content.ReadAsStringAsync();
use mockserver_client::{ClientBuilder, HttpRequest};
let client = ClientBuilder::new("localhost", 1080).build().unwrap();
let filter = HttpRequest::new().path("/some/path").method("POST");
let recorded = client.retrieve_request_responses(Some(&filter)).unwrap();
// no built-in request/response pair retrieve method; use curl
$ch = curl_init('http://localhost:1080/mockserver/retrieve?type=REQUEST_RESPONSES');
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => 'PUT',
CURLOPT_POSTFIELDS => json_encode(['path' => '/some/path', 'method' => 'POST']),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/json; charset=utf-8'],
]);
$recorded = json_decode(curl_exec($ch), true);
curl_close($ch);
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=REQUEST_RESPONSES" -d '{
"path": "/some/path",
"method": "POST"
}'
See REST API for full JSON specification
String har = new MockServerClient("localhost", 1080)
.retrieveRecordedRequestsAndResponses(
request(),
Format.HAR
);
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080)
.retrieveRecordedRequestsAndResponsesAsHar({})
.then(
function (har) {
console.log(JSON.stringify(har));
},
function (error) {
console.log(error);
}
);
See REST API for full JSON specification
import requests
# no built-in HAR retrieve method; use the REST API directly
response = requests.put(
"http://localhost:1080/mockserver/retrieve",
params={"type": "REQUEST_RESPONSES", "format": "HAR"}
)
har = response.json()
require 'net/http'
require 'json'
# no built-in HAR retrieve method; use the REST API directly
uri = URI("http://localhost:1080/mockserver/retrieve?type=REQUEST_RESPONSES&format=HAR")
response = Net::HTTP.start(uri.host, uri.port) do |http|
http.put(uri, '')
end
har = JSON.parse(response.body)
import mockserver "github.com/mock-server/mockserver-monorepo/mockserver-client-go/v7"
client := mockserver.New("localhost", 1080)
// use raw Retrieve with empty format to get HAR via query params
data, err := client.Retrieve(nil, "request_responses", "har")
using System.Net.Http;
// no built-in HAR retrieve method; use the REST API directly
using var httpClient = new HttpClient();
var response = await httpClient.PutAsync(
"http://localhost:1080/mockserver/retrieve?type=REQUEST_RESPONSES&format=HAR",
new StringContent("", System.Text.Encoding.UTF8, "application/json")
);
var har = await response.Content.ReadAsStringAsync();
use reqwest::blocking::Client;
// no built-in HAR retrieve method; use the REST API directly
let client = Client::new();
let response = client.put("http://localhost:1080/mockserver/retrieve?type=REQUEST_RESPONSES&format=HAR")
.header("Content-Type", "application/json")
.body("")
.send()
.unwrap();
let har = response.text().unwrap();
// no built-in HAR retrieve method; use curl
$ch = curl_init('http://localhost:1080/mockserver/retrieve?type=REQUEST_RESPONSES&format=HAR');
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => 'PUT',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/json; charset=utf-8'],
]);
$har = json_decode(curl_exec($ch), true);
curl_close($ch);
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=REQUEST_RESPONSES&format=HAR"
See REST API for full JSON specification
String har = new MockServerClient("localhost", 1080)
.retrieveRecordedRequestsAndResponses(
request()
.withPath("/some/path")
.withMethod("POST"),
Format.HAR
);
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).retrieveRecordedRequestsAndResponsesAsHar({
"path": "/some/path",
"method": "POST"
}).then(
function (har) {
console.log(JSON.stringify(har));
},
function (error) {
console.log(error);
}
);
See REST API for full JSON specification
import requests
# no built-in HAR retrieve method; use the REST API directly
response = requests.put(
"http://localhost:1080/mockserver/retrieve",
params={"type": "REQUEST_RESPONSES", "format": "HAR"},
json={"path": "/some/path", "method": "POST"}
)
har = response.json()
require 'net/http'
require 'json'
# no built-in HAR retrieve method; use the REST API directly
uri = URI("http://localhost:1080/mockserver/retrieve?type=REQUEST_RESPONSES&format=HAR")
response = Net::HTTP.start(uri.host, uri.port) do |http|
req = Net::HTTP::Put.new(uri)
req['Content-Type'] = 'application/json'
req.body = JSON.generate({ path: '/some/path', method: 'POST' })
http.request(req)
end
har = JSON.parse(response.body)
import mockserver "github.com/mock-server/mockserver-monorepo/mockserver-client-go/v7"
client := mockserver.New("localhost", 1080)
data, err := client.Retrieve(
mockserver.Request().Path("/some/path").Method("POST"),
"request_responses",
"har",
)
using System.Net.Http;
using System.Text;
// no built-in HAR retrieve method; use the REST API directly
using var httpClient = new HttpClient();
var json = @"{
""path"": ""/some/path"",
""method"": ""POST""
}";
var response = await httpClient.PutAsync(
"http://localhost:1080/mockserver/retrieve?type=REQUEST_RESPONSES&format=HAR",
new StringContent(json, Encoding.UTF8, "application/json")
);
var har = await response.Content.ReadAsStringAsync();
use reqwest::blocking::Client;
// no built-in HAR retrieve method; use the REST API directly
let client = Client::new();
let response = client.put("http://localhost:1080/mockserver/retrieve?type=REQUEST_RESPONSES&format=HAR")
.header("Content-Type", "application/json")
.body(r#"{"path": "/some/path", "method": "POST"}"#.to_string())
.send()
.unwrap();
let har = response.text().unwrap();
// no built-in HAR retrieve method; use curl
$ch = curl_init('http://localhost:1080/mockserver/retrieve?type=REQUEST_RESPONSES&format=HAR');
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => 'PUT',
CURLOPT_POSTFIELDS => json_encode(['path' => '/some/path', 'method' => 'POST']),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/json; charset=utf-8'],
]);
$har = json_decode(curl_exec($ch), true);
curl_close($ch);
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=REQUEST_RESPONSES&format=HAR" -d '{
"path": "/some/path",
"method": "POST"
}'
See REST API for full JSON specification