MockServer can import expectations directly from HAR (HTTP Archive) files, Postman Collection v2.x files, Pact v3 consumer contracts, and — to migrate off another mock tool — WireMock stub mappings, Mountebank imposters, and Mockoon environments. This lets you record real HTTP traffic, reuse existing collections, bootstrap stubs from a published contract, or move your whole existing mock suite into MockServer without rewriting stubs by hand.

Note: import is a server-side REST operation — all clients import by calling PUT /mockserver/import directly with the document as the request body. The examples below use curl; any HTTP client (or the language client's raw request method) sends the same request.

Common use cases:

  • Record-and-replay — capture traffic with browser DevTools (Export HAR) or Postman, then import it to create a mock that replays the recorded responses
  • Migrate existing collections — teams with an existing Postman collection can import their saved example responses into MockServer
  • Bootstrap mocks quickly — import a HAR from staging traffic to get a working mock in seconds, then fine-tune individual expectations as needed
  • Replay a Pact contract — import a Pact v3 consumer contract to create a stub provider that satisfies the contract without standing up the real service
  • Migrate off another mock tool — convert an existing WireMock, Mountebank, or Mockoon stub suite into MockServer expectations in one request, with a warning for every construct that could not be mapped 1:1
 

Import Endpoint

Send a PUT request to /mockserver/import with the HAR or Postman JSON document as the request body. MockServer creates one expectation per entry (HAR) or per saved example response (Postman) and returns 201 Created with the generated expectations as JSON.

 

Format detection

MockServer auto-detects the format from the JSON structure:

  • If the body contains log.entries, it is treated as HAR
  • If the body contains info and item, it is treated as a Postman Collection
  • If the body contains a top-level interactions array, it is treated as a Pact v3 contract
  • If the body contains a mappings array (or a stub with request.urlPath/urlPattern or a response.fault/jsonBody), it is treated as WireMock stubs
  • If the body contains an imposters array (or protocol + stubs), it is treated as Mountebank imposters
  • If the body contains a top-level routes array, it is treated as a Mockoon environment

You can also override auto-detection with the format query parameter:

Query parameter Value Description
format har Force HAR parsing
format postman Force Postman Collection parsing
format pact Force Pact v3 contract parsing
format wiremock Force WireMock stub-mapping parsing (see Migrating from WireMock, Mountebank & Mockoon)
format mountebank Force Mountebank imposter parsing
format mockoon Force Mockoon environment parsing
format recording Reload a persisted recorded-traffic NDJSON archive (see Reloading Recorded Traffic). Unlike the other formats this does not create expectations — it re-loads recorded request/response pairs so they are retrievable like live in-memory recordings. Must be specified explicitly (NDJSON is never auto-detected).

If auto-detection fails and no format parameter is provided, MockServer returns 400 Bad Request with a message suggesting you specify the format explicitly.

 

Reloading Recorded Traffic

When persistRecordedRequestsToDisk is enabled, MockServer appends every recorded exchange (both proxied and mocked request/response pairs) to a durable NDJSON archive at persistedRecordedRequestsPath. That archive outlives in-memory log eviction and restarts. Reload it with format=recording so the exchanges become retrievable exactly like live recordings via PUT /mockserver/retrieve?type=REQUEST_RESPONSES:

# reload the archive at the configured persistedRecordedRequestsPath
curl -v -X PUT "http://localhost:1080/mockserver/import?format=recording&source=disk"

# or supply an archive file in the request body
curl -v -X PUT "http://localhost:1080/mockserver/import?format=recording" \
    --data-binary @recordedRequests.ndjson

Reload is idempotent — reloaded exchanges are not written back to the archive, so reloading the same file never grows it. Sensitive-data redaction (below) applies to recording imports too.

Crash recovery. The archive is written one line at a time, so a hard crash can leave a partially-written final line. Reload skips any malformed or truncated line (reporting how many in the x-mockserver-recorded-requests-skipped response header) and still loads every intact exchange, so source=disk reliably recovers a session after a crash. An empty archive simply reloads nothing (201 with an empty list).

Note: reloaded exchanges are recorded as forwarded requests, so an originally-mocked exchange counts as forwarded if you later verify by disposition (forwarded vs mocked). This is an accepted limitation of the initial version.

Insomnia is not a supported import format — the recognised expectation formats are har, postman, pact, wiremock, mountebank, and mockoon. Export from Insomnia as HAR, or convert to a Postman collection, then import that instead.

 

Migrating from WireMock, Mountebank & Mockoon

Moving off another mock tool? Send its stub definitions to PUT /mockserver/import and MockServer converts them into expectations in one shot. Because these tools have constructs with no exact MockServer equivalent, the response body for these three formats is a JSON object with both the imported expectations and a list of structured warnings — every construct that could not be mapped 1:1 produces a warning instead of being silently dropped:

curl -v -X PUT "http://localhost:1080/mockserver/import?format=wiremock" \
    --data-binary @wiremock-mappings.json

# 201 Created
# {
#   "expectations": [ ... ],
#   "warnings": [
#     { "item": "stub[3]", "construct": "bodyPatterns.matchesXPath",
#       "detail": "XML/XPath body matching is not mapped by this importer" }
#   ]
# }

Each warning has an item (which source stub/route it came from), a construct (the foreign feature), and a detail explaining what happened. Review the warnings after a migration and add any missing matchers by hand. Secret redaction (below) applies to these imports too.

 

WireMock stub mappings

Accepts a single stub object, a { "mappings": [ ... ] } export (from GET /__admin/mappings or a mappings/ directory), or a bare JSON array. Mapping:

  • Requestmethod, urlPath (exact), urlPathPattern/urlPattern (regex path), url (path + query); queryParameters and headers predicates (equalTo, matches, contains); bodyPatterns (equalToJson, matchesJsonPath, contains, matches, equalTo).
  • Responsestatus, headers, body/base64Body/jsonBody, fixedDelayMilliseconds (delay). A fault becomes a connection-drop error; a proxyBaseUrl response becomes a forward to that host.
  • Scenarios & priority — WireMock scenarios (scenarioName/requiredScenarioState/newScenarioState) map straight onto MockServer scenarios; priority is inverted (WireMock 1 = highest).

Warned, not mapped: matchesXPath/equalToXml body matching, random delayDistribution, response templating transformers, and bodyFileName references.

 

Mountebank imposters

Accepts a single imposter, a { "imposters": [ ... ] } config, or a bare array. Only http/https imposters are imported — tcp/smtp imposters are skipped with a warning. Mapping:

  • Predicatesequals, deepEquals, contains, matches, exists, startsWith, endsWith over method/path/query/headers/body become request matchers (all predicates in a stub are combined).
  • Responsesis becomes a response, proxy becomes a forward, fault becomes a connection-drop error. _behaviors.wait becomes a delay and _behaviors.repeat becomes a repeat count. Several is responses in one stub become a single cycling response.

Warned, not mapped: tcp/smtp imposters, compound and/or/not predicates, JavaScript inject, and post-processing behaviours (decorate/copy/lookup/shellTransform).

 

Mockoon environments

Import a Mockoon environment export (a JSON file with a top-level routes array). Mapping:

  • Routemethod and endpoint become the request matcher; Express-style :param segments become single-segment wildcards.
  • ResponsestatusCode, headers, body, and latency (delay). Response rules (query/header/body targets) become extra request matchers, with descending priority so the route's response order is preserved and the default response acts as a catch-all.
  • Response modeSEQUENTIAL and RANDOM map to the matching MockServer cycling response mode.

Warned, not mapped: the crud route type, cookie/path rule targets, the null/empty_array rule operators, OR-combined rules (only the first rule maps), file-backed bodies, data buckets, and Handlebars {{...}} templating (served verbatim).

 

Sensitive Data Redaction

MockServer automatically redacts sensitive values from imported files before creating expectations, so that credentials captured in recorded traffic are not stored in your mock configuration.

Headers redacted by default: Authorization, X-Api-Key, X-Auth-Token, Cookie, Set-Cookie, Proxy-Authorization, and similar credential-bearing headers. The header name is preserved in the generated expectation but the value is replaced with a placeholder so the mock does not depend on a specific secret.

JSON body fields redacted by default: common secret field names such as password, secret, token, api_key, apiKey, access_token, and refresh_token are replaced with a placeholder value in request and response bodies.

If you need to disable redaction (for example when importing a file that contains only test credentials and you want exact value matching), or to extend the set of redacted fields for your organisation, pass import options in the query string:

Query parameter Description
redactSensitiveData=false Disable all redaction; imported values are stored as-is
additionalRedactedHeaders=X-My-Secret,X-Internal-Key Comma-separated list of extra header names to redact, in addition to the defaults
additionalRedactedBodyFields=clientSecret,privateKey Comma-separated list of extra JSON body field names to redact, in addition to the defaults
 

Importing from HAR

Each entry in the HAR's log.entries[] array produces one expectation. The request matcher uses the method, path, and query parameters from the recorded request. The response uses the recorded status code, headers, and body.

Volatile header filtering

Not all recorded headers make sense in a mock expectation. MockServer automatically filters out volatile headers that would over-constrain matching or produce stale responses:

  • Request headers excluded from matching: Host, Date, User-Agent, Accept, Accept-Encoding, Cookie, Authorization, Connection, Content-Length, Referer, Origin, trace headers, and others
  • Response headers excluded: Date, Transfer-Encoding, Content-Length, Connection, Set-Cookie, Server, Vary, trace headers, and others

Non-volatile headers (such as Content-Type) are preserved and included in the generated expectations.

Request body handling

When a HAR entry has postData.text, it is included in the request matcher if the body is reasonably sized (under 4 KB). Larger request bodies are omitted from matching to keep expectations permissive.

Consolidating a HAR into reusable mocks

A HAR captured from a browser or staging traffic often hits the same endpoint many times. By default MockServer creates one expectation per entry. Add consolidate=true (and optionally parameterize=true) to PUT /mockserver/import?format=har&consolidate=true to collapse those into a compact set of unlimited-use mocks — grouping by request shape, inferring /users/{id} path parameters from varying id segments, stripping volatile request headers, and sequencing differing responses for the same request. This is the same consolidation used by the proxy record & replay flow.

Base64 response bodies

HAR files sometimes encode response bodies as Base64 (indicated by content.encoding: "base64"). MockServer automatically decodes these back to plain text for the generated response body.

Each language client has a typed importHar helper (import_har / ImportHar) that wraps PUT /mockserver/import?format=har and returns the upserted expectations. Read the traffic.har file and pass its contents to the helper. The REST API tab shows the equivalent raw request.

import org.mockserver.client.MockServerClient;
import org.mockserver.mock.Expectation;
import java.nio.file.Files;
import java.nio.file.Path;

MockServerClient client = new MockServerClient("localhost", 1080);
String harJson = Files.readString(Path.of("traffic.har"));
Expectation[] generatedExpectations = client.importHar(harJson);
// generatedExpectations holds the upserted expectations, one per HAR entry
var mockServerClient = require('mockserver-client').mockServerClient;
var fs = require('fs');

var harJson = fs.readFileSync("traffic.har", "utf8");
mockServerClient("localhost", 1080).importHar(harJson).then(
    function (expectations) {
        console.log(expectations); // the upserted expectations, one per HAR entry
    },
    function (error) {
        console.log(error);
    }
);
from mockserver.client import MockServerClient

client = MockServerClient("localhost", 1080)
with open("traffic.har") as har:
    expectations = client.import_har(har.read())
# expectations holds the upserted expectations, one per HAR entry
require 'mockserver-client'

client = MockServer::Client.new('localhost', 1080)
expectations = client.import_har(File.read('traffic.har'))
# expectations holds the upserted expectations, one per HAR entry
import (
    "os"

    mockserver "github.com/mock-server/mockserver-monorepo/mockserver-client-go/v7"
)

client := mockserver.New("localhost", 1080)
harJSON, _ := os.ReadFile("traffic.har")
expectations, _ := client.ImportHar(string(harJSON))
// expectations holds the upserted expectations, one per HAR entry
using System.IO;
using MockServer.Client;

using var client = new MockServerClient("localhost", 1080);
var harJson = File.ReadAllText("traffic.har");
var expectations = client.ImportHar(harJson);
// expectations holds the upserted expectations, one per HAR entry
use mockserver_client::ClientBuilder;
use std::fs;

let client = ClientBuilder::new("localhost", 1080).build().unwrap();
let har_json = fs::read_to_string("traffic.har").unwrap();
let expectations = client.import_har(&har_json).unwrap();
// expectations holds the upserted expectations, one per HAR entry
use MockServer\MockServerClient;

$client = new MockServerClient('localhost', 1080);
$expectations = $client->importHar(file_get_contents('traffic.har'));
// $expectations holds the upserted expectations, one per HAR entry
curl -v -X PUT "http://localhost:1080/mockserver/import" \
  -H "Content-Type: application/json" \
  --data-binary @traffic.har

Or explicitly specify the format:

curl -v -X PUT "http://localhost:1080/mockserver/import?format=har" \
  -H "Content-Type: application/json" \
  --data-binary @traffic.har

MockServer returns 201 Created with the generated expectations as JSON.

 

Importing from Postman

MockServer supports Postman Collection v2.0 and v2.1 formats. Collections are walked recursively, so requests inside folders are imported correctly.

For each request item that has saved example responses (the response[] array), one expectation is created per example. Requests without saved examples are skipped (with a count logged), since there is no response to mock.

The Postman url field is handled whether it appears as a plain string or as the structured object format with path[] and query[] arrays.

Each language client has a typed importPostmanCollection helper (import_postman_collection / ImportPostmanCollection) that wraps PUT /mockserver/import?format=postman and returns the upserted expectations. Read the my-collection.postman_collection.json file and pass its contents to the helper. The REST API tab shows the equivalent raw request.

import org.mockserver.client.MockServerClient;
import org.mockserver.mock.Expectation;
import java.nio.file.Files;
import java.nio.file.Path;

MockServerClient client = new MockServerClient("localhost", 1080);
String postmanJson = Files.readString(Path.of("my-collection.postman_collection.json"));
Expectation[] generatedExpectations = client.importPostmanCollection(postmanJson);
// generatedExpectations holds the upserted expectations, one per saved example response
var mockServerClient = require('mockserver-client').mockServerClient;
var fs = require('fs');

var collectionJson = fs.readFileSync("my-collection.postman_collection.json", "utf8");
mockServerClient("localhost", 1080).importPostmanCollection(collectionJson).then(
    function (expectations) {
        console.log(expectations); // the upserted expectations, one per saved example response
    },
    function (error) {
        console.log(error);
    }
);
from mockserver.client import MockServerClient

client = MockServerClient("localhost", 1080)
with open("my-collection.postman_collection.json") as collection:
    expectations = client.import_postman_collection(collection.read())
# expectations holds the upserted expectations, one per saved example response
require 'mockserver-client'

client = MockServer::Client.new('localhost', 1080)
expectations = client.import_postman_collection(File.read('my-collection.postman_collection.json'))
# expectations holds the upserted expectations, one per saved example response
import (
    "os"

    mockserver "github.com/mock-server/mockserver-monorepo/mockserver-client-go/v7"
)

client := mockserver.New("localhost", 1080)
collectionJSON, _ := os.ReadFile("my-collection.postman_collection.json")
expectations, _ := client.ImportPostmanCollection(string(collectionJSON))
// expectations holds the upserted expectations, one per saved example response
using System.IO;
using MockServer.Client;

using var client = new MockServerClient("localhost", 1080);
var collectionJson = File.ReadAllText("my-collection.postman_collection.json");
var expectations = client.ImportPostmanCollection(collectionJson);
// expectations holds the upserted expectations, one per saved example response
use mockserver_client::ClientBuilder;
use std::fs;

let client = ClientBuilder::new("localhost", 1080).build().unwrap();
let collection_json = fs::read_to_string("my-collection.postman_collection.json").unwrap();
let expectations = client.import_postman_collection(&collection_json).unwrap();
// expectations holds the upserted expectations, one per saved example response
use MockServer\MockServerClient;

$client = new MockServerClient('localhost', 1080);
$expectations = $client->importPostmanCollection(file_get_contents('my-collection.postman_collection.json'));
// $expectations holds the upserted expectations, one per saved example response
curl -v -X PUT "http://localhost:1080/mockserver/import?format=postman" \
  -H "Content-Type: application/json" \
  --data-binary @my-collection.postman_collection.json

MockServer returns 201 Created with the generated expectations as JSON.

 

Importing from a Pact v3 Contract

MockServer accepts a Pact v3 consumer contract and generates one expectation per interaction. This is the inverse of the Pact export endpoint: rather than producing a contract from active expectations, it creates expectations directly from the contract, turning a published contract into a ready-to-use stub provider.

For each interaction, the importer builds:

  • A request matcher from the interaction's request object (method, path, query, headers, body)
  • A response from the interaction's response object (status, headers, body)

JSON request bodies are matched semantically (key-order and whitespace insensitive) rather than by exact string equality.

The expectation ID is set to the interaction's description field, or pact-<index> when the description is blank.

Pact matchingRules mapping

Pact v3 contracts carry optional matchingRules.request instructions that relax exact-equality matching. MockServer translates them to matcher values:

Pact rule MockServer matcher value
regex The supplied regex pattern (MockServer matches it as a regular expression)
include .*<value>.* — a substring regex
type / number / integer / decimal / boolean .+ — any non-empty value (MockServer has no first-class type matcher for string fields)
Unrecognised rule / no rule The concrete example value from the contract (exact match)

Unrecognised rule types fall back to exact matching and are logged at DEBUG.

Dedicated endpoint

A dedicated URL is also available for Pact-only imports; it behaves identically to PUT /mockserver/import?format=pact but without needing the query parameter:

PUT /mockserver/pact/import

Both the generic and dedicated endpoints accept the same redaction query parameters and return 201 Created with the generated expectations as JSON.

Each language client has a typed pactImport helper (pact_import / PactImport) that wraps the dedicated PUT /mockserver/pact/import endpoint and returns the upserted expectations. Read the consumer-provider.json contract and pass its contents to the helper. The REST API tab shows the equivalent raw request.

import org.mockserver.client.MockServerClient;
import java.nio.file.Files;
import java.nio.file.Path;

MockServerClient client = new MockServerClient("localhost", 1080);
String pactJson = Files.readString(Path.of("consumer-provider.json"));
String generatedExpectations = client.pactImport(pactJson);
// generatedExpectations holds the upserted expectations as a JSON array string
var mockServerClient = require('mockserver-client').mockServerClient;
var fs = require('fs');

var pactJson = fs.readFileSync("consumer-provider.json", "utf8");
mockServerClient("localhost", 1080).pactImport(pactJson).then(
    function (expectations) {
        console.log(expectations); // the upserted expectations, one per interaction
    },
    function (error) {
        console.log(error);
    }
);
from mockserver.client import MockServerClient

client = MockServerClient("localhost", 1080)
with open("consumer-provider.json") as pact:
    generated_expectations = client.pact_import(pact.read())
# generated_expectations holds the upserted expectations as a JSON array string
require 'mockserver-client'

client = MockServer::Client.new('localhost', 1080)
generated_expectations = client.pact_import(File.read('consumer-provider.json'))
# generated_expectations holds the upserted expectations as a JSON array string
import (
    "os"

    mockserver "github.com/mock-server/mockserver-monorepo/mockserver-client-go/v7"
)

client := mockserver.New("localhost", 1080)
pactJSON, _ := os.ReadFile("consumer-provider.json")
expectations, _ := client.PactImport(string(pactJSON))
// expectations holds the upserted expectations, one per interaction
using System.IO;
using MockServer.Client;

using var client = new MockServerClient("localhost", 1080);
var pactJson = File.ReadAllText("consumer-provider.json");
var expectations = client.PactImport(pactJson);
// expectations holds the upserted expectations, one per interaction
use mockserver_client::ClientBuilder;
use std::fs;

let client = ClientBuilder::new("localhost", 1080).build().unwrap();
let pact_json = fs::read_to_string("consumer-provider.json").unwrap();
let expectations = client.pact_import(&pact_json).unwrap();
// expectations holds the upserted expectations, one per interaction
use MockServer\MockServerClient;

$client = new MockServerClient('localhost', 1080);
$generatedExpectations = $client->pactImport(file_get_contents('consumer-provider.json'));
// $generatedExpectations holds the upserted expectations as a JSON array string
curl -v -X PUT "http://localhost:1080/mockserver/import?format=pact" \
  -H "Content-Type: application/json" \
  --data-binary @consumer-provider.json

Or use the dedicated endpoint:

curl -v -X PUT "http://localhost:1080/mockserver/pact/import" \
  -H "Content-Type: application/json" \
  --data-binary @consumer-provider.json

MockServer returns 201 Created with the generated expectations as JSON.

 

What gets generated

Each imported expectation is assigned a stable ID based on the source format and entry index (e.g. har-0, har-1, or postman-0-get-users). Re-importing the same file updates the existing expectations in place rather than creating duplicates.

The generated expectations use unlimited times and unlimited time-to-live, so they will match repeatedly until cleared or reset. You can modify individual expectations after import using the standard PUT /mockserver/expectation endpoint.

 

Error responses

Status Cause
201 Import succeeded; body contains the generated expectations as JSON
400 Empty body, invalid JSON, unrecognised format, or missing required structure (log.entries for HAR, info/item for Postman, interactions array for Pact)
 

Related Pages