The following code examples show how to create different forward actions.

new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .forward(
        forward()
            .withHost("mock-server.com")
            .withPort(80)
    );
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForward": {
        "host": "mock-server.com",
        "port": 80,
        "scheme": "HTTP"
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);

See REST API for full JSON specification

from mockserver.client import MockServerClient
from mockserver.models import HttpForward, HttpRequest

client = MockServerClient("localhost", 1080)
client.when(
    HttpRequest.request("/some/path")
).forward(
    HttpForward(host="mock-server.com", port=80, scheme="HTTP")
)
require 'mockserver-client'

client = MockServer::Client.new('localhost', 1080)
client.when(
    MockServer::HttpRequest.new(path: '/some/path')
).forward(
    MockServer::HttpForward.new(host: 'mock-server.com', port: 80, scheme: 'HTTP')
)
import mockserver "github.com/mock-server/mockserver-monorepo/mockserver-client-go/v7"

client := mockserver.New("localhost", 1080)
client.When(
    mockserver.Request().Path("/some/path"),
).Forward(
    mockserver.Forward().Host("mock-server.com").Port(80).Scheme("HTTP"),
)
using MockServer.Client;
using MockServer.Client.Models;

using var client = new MockServerClient("localhost", 1080);
client.When(
    HttpRequest.Request().WithPath("/some/path")
).Forward(
    HttpForward.Forward().WithHost("mock-server.com").WithPort(80).WithScheme("HTTP")
);
use mockserver_client::{ClientBuilder, HttpRequest, HttpForward};

let client = ClientBuilder::new("localhost", 1080).build().unwrap();
client.when(HttpRequest::new().path("/some/path"))
    .forward(HttpForward::new("mock-server.com", 80).scheme("HTTP"))
    .unwrap();
use MockServer\MockServerClient;
use MockServer\HttpRequest;
use MockServer\HttpForward;

$client = new MockServerClient('localhost', 1080);
$client->when(
    HttpRequest::request()
        ->path('/some/path')
)->forward(
    HttpForward::forward()
        ->host('mock-server.com')
        ->port(80)
        ->scheme('HTTP')
);
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForward": {
        "host": "mock-server.com",
        "port": 80,
        "scheme": "HTTP"
    }
}'

See REST API for full JSON specification

new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .forward(
        forward()
            .withHost("mock-server.com")
            .withPort(443)
            .withScheme(HttpForward.Scheme.HTTPS)
    );
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForward": {
        "host": "mock-server.com",
        "port": 443,
        "scheme": "HTTPS"
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);

See REST API for full JSON specification

from mockserver.client import MockServerClient
from mockserver.models import HttpForward, HttpRequest

client = MockServerClient("localhost", 1080)
client.when(
    HttpRequest.request("/some/path")
).forward(
    HttpForward(host="mock-server.com", port=443, scheme="HTTPS")
)
require 'mockserver-client'

client = MockServer::Client.new('localhost', 1080)
client.when(
    MockServer::HttpRequest.new(path: '/some/path')
).forward(
    MockServer::HttpForward.new(host: 'mock-server.com', port: 443, scheme: 'HTTPS')
)
import mockserver "github.com/mock-server/mockserver-monorepo/mockserver-client-go/v7"

client := mockserver.New("localhost", 1080)
client.When(
    mockserver.Request().Path("/some/path"),
).Forward(
    mockserver.Forward().Host("mock-server.com").Port(443).Scheme("HTTPS"),
)
using MockServer.Client;
using MockServer.Client.Models;

using var client = new MockServerClient("localhost", 1080);
client.When(
    HttpRequest.Request().WithPath("/some/path")
).Forward(
    HttpForward.Forward().WithHost("mock-server.com").WithPort(443).WithScheme("HTTPS")
);
use mockserver_client::{ClientBuilder, HttpRequest, HttpForward};

let client = ClientBuilder::new("localhost", 1080).build().unwrap();
client.when(HttpRequest::new().path("/some/path"))
    .forward(HttpForward::new("mock-server.com", 443).scheme("HTTPS"))
    .unwrap();
use MockServer\MockServerClient;
use MockServer\HttpRequest;
use MockServer\HttpForward;

$client = new MockServerClient('localhost', 1080);
$client->when(
    HttpRequest::request()
        ->path('/some/path')
)->forward(
    HttpForward::forward()
        ->host('mock-server.com')
        ->port(443)
        ->scheme('HTTPS')
);
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForward": {
        "host": "mock-server.com",
        "port": 443,
        "scheme": "HTTPS"
    }
}'

See REST API for full JSON specification

new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .forward(
        forwardOverriddenRequest(
            request()
                .withPath("/some/other/path")
                .withHeader("Host", "target.host.com")
        )
    );
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "headers": {
                "Host": ["target.host.com"]
            }
        }
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);

See REST API for full JSON specification

from mockserver.client import MockServerClient
from mockserver.models import Expectation

client = MockServerClient("localhost", 1080)
client.upsert(Expectation.from_dict({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "headers": {
                "Host": ["target.host.com"]
            }
        }
    }
}))
require 'mockserver-client'

client = MockServer::Client.new('localhost', 1080)
client.upsert(MockServer::Expectation.from_hash({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "headers": {
                "Host": ["target.host.com"]
            }
        }
    }
}))
package main

import (
    "bytes"
    "net/http"
)

func main() {
    body := []byte(`{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "headers": {
                "Host": ["target.host.com"]
            }
        }
    }
}`)
    req, _ := http.NewRequest("PUT",
        "http://localhost:1080/mockserver/expectation",
        bytes.NewReader(body))
    req.Header.Set("Content-Type", "application/json")
    http.DefaultClient.Do(req)
}
using System.Net.Http;
using System.Text;

using var httpClient = new HttpClient();
var json = @"{
    ""httpRequest"": {
        ""path"": ""/some/path""
    },
    ""httpOverrideForwardedRequest"": {
        ""httpRequest"": {
            ""path"": ""/some/other/path"",
            ""headers"": {
                ""Host"": [""target.host.com""]
            }
        }
    }
}";
await httpClient.PutAsync(
    "http://localhost:1080/mockserver/expectation",
    new StringContent(json, Encoding.UTF8, "application/json")
);
use reqwest::blocking::Client;

let client = Client::new();
let body = r#"{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "headers": {
                "Host": ["target.host.com"]
            }
        }
    }
}"#;
client.put("http://localhost:1080/mockserver/expectation")
    .header("Content-Type", "application/json")
    .body(body.to_string())
    .send()
    .unwrap();
$json = <<<'JSON'
{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "headers": {
                "Host": ["target.host.com"]
            }
        }
    }
}
JSON;

$ch = curl_init('http://localhost:1080/mockserver/expectation');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST  => 'PUT',
    CURLOPT_POSTFIELDS     => $json,
    CURLOPT_HTTPHEADER     => ['Content-Type: application/json; charset=utf-8'],
    CURLOPT_RETURNTRANSFER => true,
]);
curl_exec($ch);
curl_close($ch);
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "headers": {
                "Host": ["target.host.com"]
            }
        }
    }
}'

See REST API for full JSON specification

new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .forward(
        forwardOverriddenRequest(
            request()
                .withPath("/some/other/path")
                .withHeader("Host", "target.host.com"),
            response()
                .withBody("some_overridden_body")
        )
    );
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "headers": {
                "Host": ["target.host.com"]
            }
        },
        "httpResponse": {
            "body": "some_overridden_body"
        }
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);

See REST API for full JSON specification

from mockserver.client import MockServerClient
from mockserver.models import Expectation

client = MockServerClient("localhost", 1080)
client.upsert(Expectation.from_dict({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "headers": {
                "Host": ["target.host.com"]
            }
        },
        "httpResponse": {
            "body": "some_overridden_body"
        }
    }
}))
require 'mockserver-client'

client = MockServer::Client.new('localhost', 1080)
client.upsert(MockServer::Expectation.from_hash({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "headers": {
                "Host": ["target.host.com"]
            }
        },
        "httpResponse": {
            "body": "some_overridden_body"
        }
    }
}))
package main

import (
    "bytes"
    "net/http"
)

func main() {
    body := []byte(`{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "headers": {
                "Host": ["target.host.com"]
            }
        },
        "httpResponse": {
            "body": "some_overridden_body"
        }
    }
}`)
    req, _ := http.NewRequest("PUT",
        "http://localhost:1080/mockserver/expectation",
        bytes.NewReader(body))
    req.Header.Set("Content-Type", "application/json")
    http.DefaultClient.Do(req)
}
using System.Net.Http;
using System.Text;

using var httpClient = new HttpClient();
var json = @"{
    ""httpRequest"": {
        ""path"": ""/some/path""
    },
    ""httpOverrideForwardedRequest"": {
        ""httpRequest"": {
            ""path"": ""/some/other/path"",
            ""headers"": {
                ""Host"": [""target.host.com""]
            }
        },
        ""httpResponse"": {
            ""body"": ""some_overridden_body""
        }
    }
}";
await httpClient.PutAsync(
    "http://localhost:1080/mockserver/expectation",
    new StringContent(json, Encoding.UTF8, "application/json")
);
use reqwest::blocking::Client;

let client = Client::new();
let body = r#"{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "headers": {
                "Host": ["target.host.com"]
            }
        },
        "httpResponse": {
            "body": "some_overridden_body"
        }
    }
}"#;
client.put("http://localhost:1080/mockserver/expectation")
    .header("Content-Type", "application/json")
    .body(body.to_string())
    .send()
    .unwrap();
$json = <<<'JSON'
{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "headers": {
                "Host": ["target.host.com"]
            }
        },
        "httpResponse": {
            "body": "some_overridden_body"
        }
    }
}
JSON;

$ch = curl_init('http://localhost:1080/mockserver/expectation');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST  => 'PUT',
    CURLOPT_POSTFIELDS     => $json,
    CURLOPT_HTTPHEADER     => ['Content-Type: application/json; charset=utf-8'],
    CURLOPT_RETURNTRANSFER => true,
]);
curl_exec($ch);
curl_close($ch);
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "headers": {
                "Host": ["target.host.com"]
            }
        },
        "httpResponse": {
            "body": "some_overridden_body"
        }
    }
}'

See REST API for full JSON specification

new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .forward(
        forwardOverriddenRequest(
            request()
                // this replaces the entire set of headers
                .withHeader("Host", "target.host.com")
                .withBody("some_overridden_body"),
            requestModifier()
                .withPath("^/(.+)/(.+)$", "/prefix/$1/infix/$2/postfix")
                .withQueryStringParameters(
                    queryParametersModifier()
                        .add(
                            param("parameterToAddOne", "addedValue"),
                            param("parameterToAddTwo", "addedValue")
                        )
                        .replace(
                            param("overrideParameterToReplace", "replacedValue"),
                            param("requestParameterToReplace", "replacedValue"),
                            param("extraParameterToReplace", "shouldBeIgnore")
                        )
                        .remove(
                            "overrideParameterToRemove",
                            "requestParameterToRemove"
                        )

                )
                // this modifies the set of headers
                .withHeaders(
                    headersModifier()
                        .add(
                            header("headerToAddOne", "addedValue"),
                            header("headerToAddTwo", "addedValue")
                        )
                        .replace(
                            header("overrideHeaderToReplace", "replacedValue"),
                            header("requestHeaderToReplace", "replacedValue"),
                            header("extraHeaderToReplace", "shouldBeIgnore")
                        )
                        .remove(
                            "overrideHeaderToRemove",
                            "requestHeaderToRemove"
                        )

                )
                .withCookies(
                    cookiesModifier()
                        .add(
                            cookie("cookieToAddOne", "addedValue"),
                            cookie("cookieToAddTwo", "addedValue")
                        )
                        .replace(
                            cookie("overrideCookieToReplace", "replacedValue"),
                            cookie("requestCookieToReplace", "replacedValue"),
                            cookie("extraCookieToReplace", "shouldBeIgnore")
                        )
                        .remove(
                            "overrideCookieToRemove",
                            "requestCookieToRemove"
                        )

                )
        )
    );
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "requestOverride": {
            "headers": {
                "Host": [
                    "target.host.com"
                ]
            },
            "body": "some_overridden_body"
        },
        "requestModifier": {
            "cookies": {
                "add": {
                    "cookieToAddOne": "addedValue",
                    "cookieToAddTwo": "addedValue"
                },
                "remove": [
                    "overrideCookieToRemove",
                    "requestCookieToRemove"
                ],
                "replace": {
                    "overrideCookieToReplace": "replacedValue",
                    "requestCookieToReplace": "replacedValue",
                    "extraCookieToReplace": "shouldBeIgnore"
                }
            },
            "headers": {
                "add": {
                    "headerToAddTwo": [
                        "addedValue"
                    ],
                    "headerToAddOne": [
                        "addedValue"
                    ]
                },
                "remove": [
                    "overrideHeaderToRemove",
                    "requestHeaderToRemove"
                ],
                "replace": {
                    "requestHeaderToReplace": [
                        "replacedValue"
                    ],
                    "overrideHeaderToReplace": [
                        "replacedValue"
                    ],
                    "extraHeaderToReplace": [
                        "shouldBeIgnore"
                    ]
                }
            },
            "path": {
                "regex": "^/(.+)/(.+)$",
                "substitution": "/prefix/$1/infix/$2/postfix"
            },
            "queryStringParameters": {
                "add": {
                    "parameterToAddTwo": [
                        "addedValue"
                    ],
                    "parameterToAddOne": [
                        "addedValue"
                    ]
                },
                "remove": [
                    "overrideParameterToRemove",
                    "requestParameterToRemove"
                ],
                "replace": {
                    "requestParameterToReplace": [
                        "replacedValue"
                    ],
                    "overrideParameterToReplace": [
                        "replacedValue"
                    ],
                    "extraParameterToReplace": [
                        "shouldBeIgnore"
                    ]
                }
            }
        }
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);

See REST API for full JSON specification

from mockserver.client import MockServerClient
from mockserver.models import Expectation

client = MockServerClient("localhost", 1080)
client.upsert(Expectation.from_dict({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "requestOverride": {
            "headers": {
                "Host": [
                    "target.host.com"
                ]
            },
            "body": "some_overridden_body"
        },
        "requestModifier": {
            "cookies": {
                "add": {
                    "cookieToAddOne": "addedValue",
                    "cookieToAddTwo": "addedValue"
                },
                "remove": [
                    "overrideCookieToRemove",
                    "requestCookieToRemove"
                ],
                "replace": {
                    "overrideCookieToReplace": "replacedValue",
                    "requestCookieToReplace": "replacedValue",
                    "extraCookieToReplace": "shouldBeIgnore"
                }
            },
            "headers": {
                "add": {
                    "headerToAddTwo": [
                        "addedValue"
                    ],
                    "headerToAddOne": [
                        "addedValue"
                    ]
                },
                "remove": [
                    "overrideHeaderToRemove",
                    "requestHeaderToRemove"
                ],
                "replace": {
                    "requestHeaderToReplace": [
                        "replacedValue"
                    ],
                    "overrideHeaderToReplace": [
                        "replacedValue"
                    ],
                    "extraHeaderToReplace": [
                        "shouldBeIgnore"
                    ]
                }
            },
            "path": {
                "regex": "^/(.+)/(.+)$",
                "substitution": "/prefix/$1/infix/$2/postfix"
            },
            "queryStringParameters": {
                "add": {
                    "parameterToAddTwo": [
                        "addedValue"
                    ],
                    "parameterToAddOne": [
                        "addedValue"
                    ]
                },
                "remove": [
                    "overrideParameterToRemove",
                    "requestParameterToRemove"
                ],
                "replace": {
                    "requestParameterToReplace": [
                        "replacedValue"
                    ],
                    "overrideParameterToReplace": [
                        "replacedValue"
                    ],
                    "extraParameterToReplace": [
                        "shouldBeIgnore"
                    ]
                }
            }
        }
    }
}))
require 'mockserver-client'

client = MockServer::Client.new('localhost', 1080)
client.upsert(MockServer::Expectation.from_hash({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "requestOverride": {
            "headers": {
                "Host": [
                    "target.host.com"
                ]
            },
            "body": "some_overridden_body"
        },
        "requestModifier": {
            "cookies": {
                "add": {
                    "cookieToAddOne": "addedValue",
                    "cookieToAddTwo": "addedValue"
                },
                "remove": [
                    "overrideCookieToRemove",
                    "requestCookieToRemove"
                ],
                "replace": {
                    "overrideCookieToReplace": "replacedValue",
                    "requestCookieToReplace": "replacedValue",
                    "extraCookieToReplace": "shouldBeIgnore"
                }
            },
            "headers": {
                "add": {
                    "headerToAddTwo": [
                        "addedValue"
                    ],
                    "headerToAddOne": [
                        "addedValue"
                    ]
                },
                "remove": [
                    "overrideHeaderToRemove",
                    "requestHeaderToRemove"
                ],
                "replace": {
                    "requestHeaderToReplace": [
                        "replacedValue"
                    ],
                    "overrideHeaderToReplace": [
                        "replacedValue"
                    ],
                    "extraHeaderToReplace": [
                        "shouldBeIgnore"
                    ]
                }
            },
            "path": {
                "regex": "^/(.+)/(.+)$",
                "substitution": "/prefix/$1/infix/$2/postfix"
            },
            "queryStringParameters": {
                "add": {
                    "parameterToAddTwo": [
                        "addedValue"
                    ],
                    "parameterToAddOne": [
                        "addedValue"
                    ]
                },
                "remove": [
                    "overrideParameterToRemove",
                    "requestParameterToRemove"
                ],
                "replace": {
                    "requestParameterToReplace": [
                        "replacedValue"
                    ],
                    "overrideParameterToReplace": [
                        "replacedValue"
                    ],
                    "extraParameterToReplace": [
                        "shouldBeIgnore"
                    ]
                }
            }
        }
    }
}))
package main

import (
    "bytes"
    "net/http"
)

func main() {
    body := []byte(`{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "requestOverride": {
            "headers": {
                "Host": [
                    "target.host.com"
                ]
            },
            "body": "some_overridden_body"
        },
        "requestModifier": {
            "cookies": {
                "add": {
                    "cookieToAddOne": "addedValue",
                    "cookieToAddTwo": "addedValue"
                },
                "remove": [
                    "overrideCookieToRemove",
                    "requestCookieToRemove"
                ],
                "replace": {
                    "overrideCookieToReplace": "replacedValue",
                    "requestCookieToReplace": "replacedValue",
                    "extraCookieToReplace": "shouldBeIgnore"
                }
            },
            "headers": {
                "add": {
                    "headerToAddTwo": [
                        "addedValue"
                    ],
                    "headerToAddOne": [
                        "addedValue"
                    ]
                },
                "remove": [
                    "overrideHeaderToRemove",
                    "requestHeaderToRemove"
                ],
                "replace": {
                    "requestHeaderToReplace": [
                        "replacedValue"
                    ],
                    "overrideHeaderToReplace": [
                        "replacedValue"
                    ],
                    "extraHeaderToReplace": [
                        "shouldBeIgnore"
                    ]
                }
            },
            "path": {
                "regex": "^/(.+)/(.+)$",
                "substitution": "/prefix/$1/infix/$2/postfix"
            },
            "queryStringParameters": {
                "add": {
                    "parameterToAddTwo": [
                        "addedValue"
                    ],
                    "parameterToAddOne": [
                        "addedValue"
                    ]
                },
                "remove": [
                    "overrideParameterToRemove",
                    "requestParameterToRemove"
                ],
                "replace": {
                    "requestParameterToReplace": [
                        "replacedValue"
                    ],
                    "overrideParameterToReplace": [
                        "replacedValue"
                    ],
                    "extraParameterToReplace": [
                        "shouldBeIgnore"
                    ]
                }
            }
        }
    }
}`)
    req, _ := http.NewRequest("PUT",
        "http://localhost:1080/mockserver/expectation",
        bytes.NewReader(body))
    req.Header.Set("Content-Type", "application/json")
    http.DefaultClient.Do(req)
}
using System.Net.Http;
using System.Text;

using var httpClient = new HttpClient();
var json = @"{
    ""httpRequest"": {
        ""path"": ""/some/path""
    },
    ""httpOverrideForwardedRequest"": {
        ""requestOverride"": {
            ""headers"": {
                ""Host"": [
                    ""target.host.com""
                ]
            },
            ""body"": ""some_overridden_body""
        },
        ""requestModifier"": {
            ""cookies"": {
                ""add"": {
                    ""cookieToAddOne"": ""addedValue"",
                    ""cookieToAddTwo"": ""addedValue""
                },
                ""remove"": [
                    ""overrideCookieToRemove"",
                    ""requestCookieToRemove""
                ],
                ""replace"": {
                    ""overrideCookieToReplace"": ""replacedValue"",
                    ""requestCookieToReplace"": ""replacedValue"",
                    ""extraCookieToReplace"": ""shouldBeIgnore""
                }
            },
            ""headers"": {
                ""add"": {
                    ""headerToAddTwo"": [
                        ""addedValue""
                    ],
                    ""headerToAddOne"": [
                        ""addedValue""
                    ]
                },
                ""remove"": [
                    ""overrideHeaderToRemove"",
                    ""requestHeaderToRemove""
                ],
                ""replace"": {
                    ""requestHeaderToReplace"": [
                        ""replacedValue""
                    ],
                    ""overrideHeaderToReplace"": [
                        ""replacedValue""
                    ],
                    ""extraHeaderToReplace"": [
                        ""shouldBeIgnore""
                    ]
                }
            },
            ""path"": {
                ""regex"": ""^/(.+)/(.+)$"",
                ""substitution"": ""/prefix/$1/infix/$2/postfix""
            },
            ""queryStringParameters"": {
                ""add"": {
                    ""parameterToAddTwo"": [
                        ""addedValue""
                    ],
                    ""parameterToAddOne"": [
                        ""addedValue""
                    ]
                },
                ""remove"": [
                    ""overrideParameterToRemove"",
                    ""requestParameterToRemove""
                ],
                ""replace"": {
                    ""requestParameterToReplace"": [
                        ""replacedValue""
                    ],
                    ""overrideParameterToReplace"": [
                        ""replacedValue""
                    ],
                    ""extraParameterToReplace"": [
                        ""shouldBeIgnore""
                    ]
                }
            }
        }
    }
}";
await httpClient.PutAsync(
    "http://localhost:1080/mockserver/expectation",
    new StringContent(json, Encoding.UTF8, "application/json")
);
use reqwest::blocking::Client;

let client = Client::new();
let body = r#"{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "requestOverride": {
            "headers": {
                "Host": [
                    "target.host.com"
                ]
            },
            "body": "some_overridden_body"
        },
        "requestModifier": {
            "cookies": {
                "add": {
                    "cookieToAddOne": "addedValue",
                    "cookieToAddTwo": "addedValue"
                },
                "remove": [
                    "overrideCookieToRemove",
                    "requestCookieToRemove"
                ],
                "replace": {
                    "overrideCookieToReplace": "replacedValue",
                    "requestCookieToReplace": "replacedValue",
                    "extraCookieToReplace": "shouldBeIgnore"
                }
            },
            "headers": {
                "add": {
                    "headerToAddTwo": [
                        "addedValue"
                    ],
                    "headerToAddOne": [
                        "addedValue"
                    ]
                },
                "remove": [
                    "overrideHeaderToRemove",
                    "requestHeaderToRemove"
                ],
                "replace": {
                    "requestHeaderToReplace": [
                        "replacedValue"
                    ],
                    "overrideHeaderToReplace": [
                        "replacedValue"
                    ],
                    "extraHeaderToReplace": [
                        "shouldBeIgnore"
                    ]
                }
            },
            "path": {
                "regex": "^/(.+)/(.+)$",
                "substitution": "/prefix/$1/infix/$2/postfix"
            },
            "queryStringParameters": {
                "add": {
                    "parameterToAddTwo": [
                        "addedValue"
                    ],
                    "parameterToAddOne": [
                        "addedValue"
                    ]
                },
                "remove": [
                    "overrideParameterToRemove",
                    "requestParameterToRemove"
                ],
                "replace": {
                    "requestParameterToReplace": [
                        "replacedValue"
                    ],
                    "overrideParameterToReplace": [
                        "replacedValue"
                    ],
                    "extraParameterToReplace": [
                        "shouldBeIgnore"
                    ]
                }
            }
        }
    }
}"#;
client.put("http://localhost:1080/mockserver/expectation")
    .header("Content-Type", "application/json")
    .body(body.to_string())
    .send()
    .unwrap();
$json = <<<'JSON'
{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "requestOverride": {
            "headers": {
                "Host": [
                    "target.host.com"
                ]
            },
            "body": "some_overridden_body"
        },
        "requestModifier": {
            "cookies": {
                "add": {
                    "cookieToAddOne": "addedValue",
                    "cookieToAddTwo": "addedValue"
                },
                "remove": [
                    "overrideCookieToRemove",
                    "requestCookieToRemove"
                ],
                "replace": {
                    "overrideCookieToReplace": "replacedValue",
                    "requestCookieToReplace": "replacedValue",
                    "extraCookieToReplace": "shouldBeIgnore"
                }
            },
            "headers": {
                "add": {
                    "headerToAddTwo": [
                        "addedValue"
                    ],
                    "headerToAddOne": [
                        "addedValue"
                    ]
                },
                "remove": [
                    "overrideHeaderToRemove",
                    "requestHeaderToRemove"
                ],
                "replace": {
                    "requestHeaderToReplace": [
                        "replacedValue"
                    ],
                    "overrideHeaderToReplace": [
                        "replacedValue"
                    ],
                    "extraHeaderToReplace": [
                        "shouldBeIgnore"
                    ]
                }
            },
            "path": {
                "regex": "^/(.+)/(.+)$",
                "substitution": "/prefix/$1/infix/$2/postfix"
            },
            "queryStringParameters": {
                "add": {
                    "parameterToAddTwo": [
                        "addedValue"
                    ],
                    "parameterToAddOne": [
                        "addedValue"
                    ]
                },
                "remove": [
                    "overrideParameterToRemove",
                    "requestParameterToRemove"
                ],
                "replace": {
                    "requestParameterToReplace": [
                        "replacedValue"
                    ],
                    "overrideParameterToReplace": [
                        "replacedValue"
                    ],
                    "extraParameterToReplace": [
                        "shouldBeIgnore"
                    ]
                }
            }
        }
    }
}
JSON;

$ch = curl_init('http://localhost:1080/mockserver/expectation');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST  => 'PUT',
    CURLOPT_POSTFIELDS     => $json,
    CURLOPT_HTTPHEADER     => ['Content-Type: application/json; charset=utf-8'],
    CURLOPT_RETURNTRANSFER => true,
]);
curl_exec($ch);
curl_close($ch);
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "requestOverride": {
            "headers": {
                "Host": [
                    "target.host.com"
                ]
            },
            "body": "some_overridden_body"
        },
        "requestModifier": {
            "cookies": {
                "add": {
                    "cookieToAddOne": "addedValue",
                    "cookieToAddTwo": "addedValue"
                },
                "remove": [
                    "overrideCookieToRemove",
                    "requestCookieToRemove"
                ],
                "replace": {
                    "overrideCookieToReplace": "replacedValue",
                    "requestCookieToReplace": "replacedValue",
                    "extraCookieToReplace": "shouldBeIgnore"
                }
            },
            "headers": {
                "add": {
                    "headerToAddTwo": [
                        "addedValue"
                    ],
                    "headerToAddOne": [
                        "addedValue"
                    ]
                },
                "remove": [
                    "overrideHeaderToRemove",
                    "requestHeaderToRemove"
                ],
                "replace": {
                    "requestHeaderToReplace": [
                        "replacedValue"
                    ],
                    "overrideHeaderToReplace": [
                        "replacedValue"
                    ],
                    "extraHeaderToReplace": [
                        "shouldBeIgnore"
                    ]
                }
            },
            "path": {
                "regex": "^/(.+)/(.+)$",
                "substitution": "/prefix/$1/infix/$2/postfix"
            },
            "queryStringParameters": {
                "add": {
                    "parameterToAddTwo": [
                        "addedValue"
                    ],
                    "parameterToAddOne": [
                        "addedValue"
                    ]
                },
                "remove": [
                    "overrideParameterToRemove",
                    "requestParameterToRemove"
                ],
                "replace": {
                    "requestParameterToReplace": [
                        "replacedValue"
                    ],
                    "overrideParameterToReplace": [
                        "replacedValue"
                    ],
                    "extraParameterToReplace": [
                        "shouldBeIgnore"
                    ]
                }
            }
        }
    }
}'

See REST API for full JSON specification

new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .forward(
        forwardOverriddenRequest()
            .withRequestOverride(
                request()
                    // this replaces the entire set of headers
                    .withHeader("Host", "target.host.com")
                    .withBody("some_overridden_body")
            )
            .withRequestModifier(
                requestModifier()
                    .withPath("^/(.+)/(.+)$", "/prefix/$1/infix/$2/postfix")
                    .withQueryStringParameters(
                        queryParametersModifier()
                            .add(
                                param("parameterToAddOne", "addedValue"),
                                param("parameterToAddTwo", "addedValue")
                            )
                            .replace(
                                param("overrideParameterToReplace", "replacedValue"),
                                param("requestParameterToReplace", "replacedValue"),
                                param("extraParameterToReplace", "shouldBeIgnore")
                            )
                            .remove(
                                "overrideParameterToRemove",
                                "requestParameterToRemove"
                            )

                    )
                    // this modifies the set of headers
                    .withHeaders(
                        headersModifier()
                            .add(
                                header("headerToAddOne", "addedValue"),
                                header("headerToAddTwo", "addedValue")
                            )
                            .replace(
                                header("overrideHeaderToReplace", "replacedValue"),
                                header("requestHeaderToReplace", "replacedValue"),
                                header("extraHeaderToReplace", "shouldBeIgnore")
                            )
                            .remove(
                                "overrideHeaderToRemove",
                                "requestHeaderToRemove"
                            )

                    )
                    .withCookies(
                        cookiesModifier()
                            .add(
                                cookie("cookieToAddOne", "addedValue"),
                                cookie("cookieToAddTwo", "addedValue")
                            )
                            .replace(
                                cookie("overrideCookieToReplace", "replacedValue"),
                                cookie("requestCookieToReplace", "replacedValue"),
                                cookie("extraCookieToReplace", "shouldBeIgnore")
                            )
                            .remove(
                                "overrideCookieToRemove",
                                "requestCookieToRemove"
                            )

                    )
            )
            .withResponseOverride(
                response()
                    .withBody("some_overridden_body")
            )
            .withResponseModifier(
                responseModifier()
                    .withHeaders(
                        headersModifier()
                            .add(
                                header("headerToAddOne", "addedValue"),
                                header("headerToAddTwo", "addedValue")
                            )
                            .replace(
                                header("overrideHeaderToReplace", "replacedValue"),
                                header("requestHeaderToReplace", "replacedValue"),
                                header("extraHeaderToReplace", "shouldBeIgnore")
                            )
                            .remove(
                                "overrideHeaderToRemove",
                                "requestHeaderToRemove"
                            )

                    )
                    .withCookies(
                        cookiesModifier()
                            .add(
                                cookie("cookieToAddOne", "addedValue"),
                                cookie("cookieToAddTwo", "addedValue")
                            )
                            .replace(
                                cookie("overrideCookieToReplace", "replacedValue"),
                                cookie("requestCookieToReplace", "replacedValue"),
                                cookie("extraCookieToReplace", "shouldBeIgnore")
                            )
                            .remove(
                                "overrideCookieToRemove",
                                "requestCookieToRemove"
                            )

                    )
            )
    );
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "requestOverride": {
            "headers": {
                "Host": [
                    "target.host.com"
                ]
            },
            "body": "some_overridden_body"
        },
        "requestModifier": {
            "cookies": {
                "add": {
                    "cookieToAddOne": "addedValue",
                    "cookieToAddTwo": "addedValue"
                },
                "remove": [
                    "overrideCookieToRemove",
                    "requestCookieToRemove"
                ],
                "replace": {
                    "overrideCookieToReplace": "replacedValue",
                    "requestCookieToReplace": "replacedValue",
                    "extraCookieToReplace": "shouldBeIgnore"
                }
            },
            "headers": {
                "add": {
                    "headerToAddTwo": [
                        "addedValue"
                    ],
                    "headerToAddOne": [
                        "addedValue"
                    ]
                },
                "remove": [
                    "overrideHeaderToRemove",
                    "requestHeaderToRemove"
                ],
                "replace": {
                    "requestHeaderToReplace": [
                        "replacedValue"
                    ],
                    "overrideHeaderToReplace": [
                        "replacedValue"
                    ],
                    "extraHeaderToReplace": [
                        "shouldBeIgnore"
                    ]
                }
            },
            "path": {
                "regex": "^/(.+)/(.+)$",
                "substitution": "/prefix/$1/infix/$2/postfix"
            },
            "queryStringParameters": {
                "add": {
                    "parameterToAddTwo": [
                        "addedValue"
                    ],
                    "parameterToAddOne": [
                        "addedValue"
                    ]
                },
                "remove": [
                    "overrideParameterToRemove",
                    "requestParameterToRemove"
                ],
                "replace": {
                    "requestParameterToReplace": [
                        "replacedValue"
                    ],
                    "overrideParameterToReplace": [
                        "replacedValue"
                    ],
                    "extraParameterToReplace": [
                        "shouldBeIgnore"
                    ]
                }
            }
        },
        "responseOverride": {
            "body": "some_overridden_body"
        },
        "responseModifier": {
            "cookies": {
                "add": {
                    "cookieToAddOne": "addedValue",
                    "cookieToAddTwo": "addedValue"
                },
                "remove": [
                    "overrideCookieToRemove",
                    "requestCookieToRemove"
                ],
                "replace": {
                    "overrideCookieToReplace": "replacedValue",
                    "requestCookieToReplace": "replacedValue",
                    "extraCookieToReplace": "shouldBeIgnore"
                }
            },
            "headers": {
                "add": {
                    "headerToAddTwo": [
                        "addedValue"
                    ],
                    "headerToAddOne": [
                        "addedValue"
                    ]
                },
                "remove": [
                    "overrideHeaderToRemove",
                    "requestHeaderToRemove"
                ],
                "replace": {
                    "requestHeaderToReplace": [
                        "replacedValue"
                    ],
                    "overrideHeaderToReplace": [
                        "replacedValue"
                    ],
                    "extraHeaderToReplace": [
                        "shouldBeIgnore"
                    ]
                }
            }
        }
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);

See REST API for full JSON specification

from mockserver.client import MockServerClient
from mockserver.models import Expectation

client = MockServerClient("localhost", 1080)
client.upsert(Expectation.from_dict({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "requestOverride": {
            "headers": {
                "Host": [
                    "target.host.com"
                ]
            },
            "body": "some_overridden_body"
        },
        "requestModifier": {
            "cookies": {
                "add": {
                    "cookieToAddOne": "addedValue",
                    "cookieToAddTwo": "addedValue"
                },
                "remove": [
                    "overrideCookieToRemove",
                    "requestCookieToRemove"
                ],
                "replace": {
                    "overrideCookieToReplace": "replacedValue",
                    "requestCookieToReplace": "replacedValue",
                    "extraCookieToReplace": "shouldBeIgnore"
                }
            },
            "headers": {
                "add": {
                    "headerToAddTwo": [
                        "addedValue"
                    ],
                    "headerToAddOne": [
                        "addedValue"
                    ]
                },
                "remove": [
                    "overrideHeaderToRemove",
                    "requestHeaderToRemove"
                ],
                "replace": {
                    "requestHeaderToReplace": [
                        "replacedValue"
                    ],
                    "overrideHeaderToReplace": [
                        "replacedValue"
                    ],
                    "extraHeaderToReplace": [
                        "shouldBeIgnore"
                    ]
                }
            },
            "path": {
                "regex": "^/(.+)/(.+)$",
                "substitution": "/prefix/$1/infix/$2/postfix"
            },
            "queryStringParameters": {
                "add": {
                    "parameterToAddTwo": [
                        "addedValue"
                    ],
                    "parameterToAddOne": [
                        "addedValue"
                    ]
                },
                "remove": [
                    "overrideParameterToRemove",
                    "requestParameterToRemove"
                ],
                "replace": {
                    "requestParameterToReplace": [
                        "replacedValue"
                    ],
                    "overrideParameterToReplace": [
                        "replacedValue"
                    ],
                    "extraParameterToReplace": [
                        "shouldBeIgnore"
                    ]
                }
            }
        },
        "responseOverride": {
            "body": "some_overridden_body"
        },
        "responseModifier": {
            "cookies": {
                "add": {
                    "cookieToAddOne": "addedValue",
                    "cookieToAddTwo": "addedValue"
                },
                "remove": [
                    "overrideCookieToRemove",
                    "requestCookieToRemove"
                ],
                "replace": {))
require 'mockserver-client'

client = MockServer::Client.new('localhost', 1080)
client.upsert(MockServer::Expectation.from_hash({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "requestOverride": {
            "headers": {
                "Host": [
                    "target.host.com"
                ]
            },
            "body": "some_overridden_body"
        },
        "requestModifier": {
            "cookies": {
                "add": {
                    "cookieToAddOne": "addedValue",
                    "cookieToAddTwo": "addedValue"
                },
                "remove": [
                    "overrideCookieToRemove",
                    "requestCookieToRemove"
                ],
                "replace": {
                    "overrideCookieToReplace": "replacedValue",
                    "requestCookieToReplace": "replacedValue",
                    "extraCookieToReplace": "shouldBeIgnore"
                }
            },
            "headers": {
                "add": {
                    "headerToAddTwo": [
                        "addedValue"
                    ],
                    "headerToAddOne": [
                        "addedValue"
                    ]
                },
                "remove": [
                    "overrideHeaderToRemove",
                    "requestHeaderToRemove"
                ],
                "replace": {
                    "requestHeaderToReplace": [
                        "replacedValue"
                    ],
                    "overrideHeaderToReplace": [
                        "replacedValue"
                    ],
                    "extraHeaderToReplace": [
                        "shouldBeIgnore"
                    ]
                }
            },
            "path": {
                "regex": "^/(.+)/(.+)$",
                "substitution": "/prefix/$1/infix/$2/postfix"
            },
            "queryStringParameters": {
                "add": {
                    "parameterToAddTwo": [
                        "addedValue"
                    ],
                    "parameterToAddOne": [
                        "addedValue"
                    ]
                },
                "remove": [
                    "overrideParameterToRemove",
                    "requestParameterToRemove"
                ],
                "replace": {
                    "requestParameterToReplace": [
                        "replacedValue"
                    ],
                    "overrideParameterToReplace": [
                        "replacedValue"
                    ],
                    "extraParameterToReplace": [
                        "shouldBeIgnore"
                    ]
                }
            }
        },
        "responseOverride": {
            "body": "some_overridden_body"
        },
        "responseModifier": {
            "cookies": {
                "add": {
                    "cookieToAddOne": "addedValue",
                    "cookieToAddTwo": "addedValue"
                },
                "remove": [
                    "overrideCookieToRemove",
                    "requestCookieToRemove"
                ],
                "replace": {))
package main

import (
    "bytes"
    "net/http"
)

func main() {
    body := []byte(`{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "requestOverride": {
            "headers": {
                "Host": [
                    "target.host.com"
                ]
            },
            "body": "some_overridden_body"
        },
        "requestModifier": {
            "cookies": {
                "add": {
                    "cookieToAddOne": "addedValue",
                    "cookieToAddTwo": "addedValue"
                },
                "remove": [
                    "overrideCookieToRemove",
                    "requestCookieToRemove"
                ],
                "replace": {
                    "overrideCookieToReplace": "replacedValue",
                    "requestCookieToReplace": "replacedValue",
                    "extraCookieToReplace": "shouldBeIgnore"
                }
            },
            "headers": {
                "add": {
                    "headerToAddTwo": [
                        "addedValue"
                    ],
                    "headerToAddOne": [
                        "addedValue"
                    ]
                },
                "remove": [
                    "overrideHeaderToRemove",
                    "requestHeaderToRemove"
                ],
                "replace": {
                    "requestHeaderToReplace": [
                        "replacedValue"
                    ],
                    "overrideHeaderToReplace": [
                        "replacedValue"
                    ],
                    "extraHeaderToReplace": [
                        "shouldBeIgnore"
                    ]
                }
            },
            "path": {
                "regex": "^/(.+)/(.+)$",
                "substitution": "/prefix/$1/infix/$2/postfix"
            },
            "queryStringParameters": {
                "add": {
                    "parameterToAddTwo": [
                        "addedValue"
                    ],
                    "parameterToAddOne": [
                        "addedValue"
                    ]
                },
                "remove": [
                    "overrideParameterToRemove",
                    "requestParameterToRemove"
                ],
                "replace": {
                    "requestParameterToReplace": [
                        "replacedValue"
                    ],
                    "overrideParameterToReplace": [
                        "replacedValue"
                    ],
                    "extraParameterToReplace": [
                        "shouldBeIgnore"
                    ]
                }
            }
        },
        "responseOverride": {
            "body": "some_overridden_body"
        },
        "responseModifier": {
            "cookies": {
                "add": {
                    "cookieToAddOne": "addedValue",
                    "cookieToAddTwo": "addedValue"
                },
                "remove": [
                    "overrideCookieToRemove",
                    "requestCookieToRemove"
                ],
                "replace": {`)
    req, _ := http.NewRequest("PUT",
        "http://localhost:1080/mockserver/expectation",
        bytes.NewReader(body))
    req.Header.Set("Content-Type", "application/json")
    http.DefaultClient.Do(req)
}
using System.Net.Http;
using System.Text;

using var httpClient = new HttpClient();
var json = @"{
    ""httpRequest"": {
        ""path"": ""/some/path""
    },
    ""httpOverrideForwardedRequest"": {
        ""requestOverride"": {
            ""headers"": {
                ""Host"": [
                    ""target.host.com""
                ]
            },
            ""body"": ""some_overridden_body""
        },
        ""requestModifier"": {
            ""cookies"": {
                ""add"": {
                    ""cookieToAddOne"": ""addedValue"",
                    ""cookieToAddTwo"": ""addedValue""
                },
                ""remove"": [
                    ""overrideCookieToRemove"",
                    ""requestCookieToRemove""
                ],
                ""replace"": {
                    ""overrideCookieToReplace"": ""replacedValue"",
                    ""requestCookieToReplace"": ""replacedValue"",
                    ""extraCookieToReplace"": ""shouldBeIgnore""
                }
            },
            ""headers"": {
                ""add"": {
                    ""headerToAddTwo"": [
                        ""addedValue""
                    ],
                    ""headerToAddOne"": [
                        ""addedValue""
                    ]
                },
                ""remove"": [
                    ""overrideHeaderToRemove"",
                    ""requestHeaderToRemove""
                ],
                ""replace"": {
                    ""requestHeaderToReplace"": [
                        ""replacedValue""
                    ],
                    ""overrideHeaderToReplace"": [
                        ""replacedValue""
                    ],
                    ""extraHeaderToReplace"": [
                        ""shouldBeIgnore""
                    ]
                }
            },
            ""path"": {
                ""regex"": ""^/(.+)/(.+)$"",
                ""substitution"": ""/prefix/$1/infix/$2/postfix""
            },
            ""queryStringParameters"": {
                ""add"": {
                    ""parameterToAddTwo"": [
                        ""addedValue""
                    ],
                    ""parameterToAddOne"": [
                        ""addedValue""
                    ]
                },
                ""remove"": [
                    ""overrideParameterToRemove"",
                    ""requestParameterToRemove""
                ],
                ""replace"": {
                    ""requestParameterToReplace"": [
                        ""replacedValue""
                    ],
                    ""overrideParameterToReplace"": [
                        ""replacedValue""
                    ],
                    ""extraParameterToReplace"": [
                        ""shouldBeIgnore""
                    ]
                }
            }
        },
        ""responseOverride"": {
            ""body"": ""some_overridden_body""
        },
        ""responseModifier"": {
            ""cookies"": {
                ""add"": {
                    ""cookieToAddOne"": ""addedValue"",
                    ""cookieToAddTwo"": ""addedValue""
                },
                ""remove"": [
                    ""overrideCookieToRemove"",
                    ""requestCookieToRemove""
                ],
                ""replace"": {";
await httpClient.PutAsync(
    "http://localhost:1080/mockserver/expectation",
    new StringContent(json, Encoding.UTF8, "application/json")
);
use reqwest::blocking::Client;

let client = Client::new();
let body = r#"{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "requestOverride": {
            "headers": {
                "Host": [
                    "target.host.com"
                ]
            },
            "body": "some_overridden_body"
        },
        "requestModifier": {
            "cookies": {
                "add": {
                    "cookieToAddOne": "addedValue",
                    "cookieToAddTwo": "addedValue"
                },
                "remove": [
                    "overrideCookieToRemove",
                    "requestCookieToRemove"
                ],
                "replace": {
                    "overrideCookieToReplace": "replacedValue",
                    "requestCookieToReplace": "replacedValue",
                    "extraCookieToReplace": "shouldBeIgnore"
                }
            },
            "headers": {
                "add": {
                    "headerToAddTwo": [
                        "addedValue"
                    ],
                    "headerToAddOne": [
                        "addedValue"
                    ]
                },
                "remove": [
                    "overrideHeaderToRemove",
                    "requestHeaderToRemove"
                ],
                "replace": {
                    "requestHeaderToReplace": [
                        "replacedValue"
                    ],
                    "overrideHeaderToReplace": [
                        "replacedValue"
                    ],
                    "extraHeaderToReplace": [
                        "shouldBeIgnore"
                    ]
                }
            },
            "path": {
                "regex": "^/(.+)/(.+)$",
                "substitution": "/prefix/$1/infix/$2/postfix"
            },
            "queryStringParameters": {
                "add": {
                    "parameterToAddTwo": [
                        "addedValue"
                    ],
                    "parameterToAddOne": [
                        "addedValue"
                    ]
                },
                "remove": [
                    "overrideParameterToRemove",
                    "requestParameterToRemove"
                ],
                "replace": {
                    "requestParameterToReplace": [
                        "replacedValue"
                    ],
                    "overrideParameterToReplace": [
                        "replacedValue"
                    ],
                    "extraParameterToReplace": [
                        "shouldBeIgnore"
                    ]
                }
            }
        },
        "responseOverride": {
            "body": "some_overridden_body"
        },
        "responseModifier": {
            "cookies": {
                "add": {
                    "cookieToAddOne": "addedValue",
                    "cookieToAddTwo": "addedValue"
                },
                "remove": [
                    "overrideCookieToRemove",
                    "requestCookieToRemove"
                ],
                "replace": {"#;
client.put("http://localhost:1080/mockserver/expectation")
    .header("Content-Type", "application/json")
    .body(body.to_string())
    .send()
    .unwrap();
$json = <<<'JSON'
{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "requestOverride": {
            "headers": {
                "Host": [
                    "target.host.com"
                ]
            },
            "body": "some_overridden_body"
        },
        "requestModifier": {
            "cookies": {
                "add": {
                    "cookieToAddOne": "addedValue",
                    "cookieToAddTwo": "addedValue"
                },
                "remove": [
                    "overrideCookieToRemove",
                    "requestCookieToRemove"
                ],
                "replace": {
                    "overrideCookieToReplace": "replacedValue",
                    "requestCookieToReplace": "replacedValue",
                    "extraCookieToReplace": "shouldBeIgnore"
                }
            },
            "headers": {
                "add": {
                    "headerToAddTwo": [
                        "addedValue"
                    ],
                    "headerToAddOne": [
                        "addedValue"
                    ]
                },
                "remove": [
                    "overrideHeaderToRemove",
                    "requestHeaderToRemove"
                ],
                "replace": {
                    "requestHeaderToReplace": [
                        "replacedValue"
                    ],
                    "overrideHeaderToReplace": [
                        "replacedValue"
                    ],
                    "extraHeaderToReplace": [
                        "shouldBeIgnore"
                    ]
                }
            },
            "path": {
                "regex": "^/(.+)/(.+)$",
                "substitution": "/prefix/$1/infix/$2/postfix"
            },
            "queryStringParameters": {
                "add": {
                    "parameterToAddTwo": [
                        "addedValue"
                    ],
                    "parameterToAddOne": [
                        "addedValue"
                    ]
                },
                "remove": [
                    "overrideParameterToRemove",
                    "requestParameterToRemove"
                ],
                "replace": {
                    "requestParameterToReplace": [
                        "replacedValue"
                    ],
                    "overrideParameterToReplace": [
                        "replacedValue"
                    ],
                    "extraParameterToReplace": [
                        "shouldBeIgnore"
                    ]
                }
            }
        },
        "responseOverride": {
            "body": "some_overridden_body"
        },
        "responseModifier": {
            "cookies": {
                "add": {
                    "cookieToAddOne": "addedValue",
                    "cookieToAddTwo": "addedValue"
                },
                "remove": [
                    "overrideCookieToRemove",
                    "requestCookieToRemove"
                ],
                "replace": {
                    "overrideCookieToReplace": "replacedValue",
                    "requestCookieToReplace": "replacedValue",
                    "extraCookieToReplace": "shouldBeIgnore"
                }
            },
            "headers": {
                "add": {
                    "headerToAddTwo": [
                        "addedValue"
                    ],
                    "headerToAddOne": [
                        "addedValue"
                    ]
                },
                "remove": [
                    "overrideHeaderToRemove",
                    "requestHeaderToRemove"
                ],
                "replace": {
                    "requestHeaderToReplace": [
                        "replacedValue"
                    ],
                    "overrideHeaderToReplace": [
                        "replacedValue"
                    ],
                    "extraHeaderToReplace": [
                        "shouldBeIgnore"
                    ]
                }
            }
        }
    }
}
JSON;

$ch = curl_init('http://localhost:1080/mockserver/expectation');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST  => 'PUT',
    CURLOPT_POSTFIELDS     => $json,
    CURLOPT_HTTPHEADER     => ['Content-Type: application/json; charset=utf-8'],
    CURLOPT_RETURNTRANSFER => true,
]);
curl_exec($ch);
curl_close($ch);
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "requestOverride": {
            "headers": {
                "Host": [
                    "target.host.com"
                ]
            },
            "body": "some_overridden_body"
        },
        "requestModifier": {
            "cookies": {
                "add": {
                    "cookieToAddOne": "addedValue",
                    "cookieToAddTwo": "addedValue"
                },
                "remove": [
                    "overrideCookieToRemove",
                    "requestCookieToRemove"
                ],
                "replace": {
                    "overrideCookieToReplace": "replacedValue",
                    "requestCookieToReplace": "replacedValue",
                    "extraCookieToReplace": "shouldBeIgnore"
                }
            },
            "headers": {
                "add": {
                    "headerToAddTwo": [
                        "addedValue"
                    ],
                    "headerToAddOne": [
                        "addedValue"
                    ]
                },
                "remove": [
                    "overrideHeaderToRemove",
                    "requestHeaderToRemove"
                ],
                "replace": {
                    "requestHeaderToReplace": [
                        "replacedValue"
                    ],
                    "overrideHeaderToReplace": [
                        "replacedValue"
                    ],
                    "extraHeaderToReplace": [
                        "shouldBeIgnore"
                    ]
                }
            },
            "path": {
                "regex": "^/(.+)/(.+)$",
                "substitution": "/prefix/$1/infix/$2/postfix"
            },
            "queryStringParameters": {
                "add": {
                    "parameterToAddTwo": [
                        "addedValue"
                    ],
                    "parameterToAddOne": [
                        "addedValue"
                    ]
                },
                "remove": [
                    "overrideParameterToRemove",
                    "requestParameterToRemove"
                ],
                "replace": {
                    "requestParameterToReplace": [
                        "replacedValue"
                    ],
                    "overrideParameterToReplace": [
                        "replacedValue"
                    ],
                    "extraParameterToReplace": [
                        "shouldBeIgnore"
                    ]
                }
            }
        },
        "responseOverride": {
            "body": "some_overridden_body"
        },
        "responseModifier": {
            "cookies": {
                "add": {
                    "cookieToAddOne": "addedValue",
                    "cookieToAddTwo": "addedValue"
                },
                "remove": [
                    "overrideCookieToRemove",
                    "requestCookieToRemove"
                ],
                "replace": {
                    "overrideCookieToReplace": "replacedValue",
                    "requestCookieToReplace": "replacedValue",
                    "extraCookieToReplace": "shouldBeIgnore"
                }
            },
            "headers": {
                "add": {
                    "headerToAddTwo": [
                        "addedValue"
                    ],
                    "headerToAddOne": [
                        "addedValue"
                    ]
                },
                "remove": [
                    "overrideHeaderToRemove",
                    "requestHeaderToRemove"
                ],
                "replace": {
                    "requestHeaderToReplace": [
                        "replacedValue"
                    ],
                    "overrideHeaderToReplace": [
                        "replacedValue"
                    ],
                    "extraHeaderToReplace": [
                        "shouldBeIgnore"
                    ]
                }
            }
        }
    }
}'

See REST API for full JSON specification

new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .forward(
        forwardOverriddenRequest(
            request()
                .withPath("/some/other/path")
                .withHeader("Host", "any.host.com")
                .withSocketAddress("target.host.com", 1234, SocketAddress.Scheme.HTTPS)
        )
    );
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "headers": {
                "Host": ["any.host.com"]
            },
            "socketAddress": {
                "host": "target.host.com",
                "port": 1234,
                "scheme": "HTTPS"
            }
        }
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);

See REST API for full JSON specification

from mockserver.client import MockServerClient
from mockserver.models import Expectation

client = MockServerClient("localhost", 1080)
client.upsert(Expectation.from_dict({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "headers": {
                "Host": ["any.host.com"]
            },
            "socketAddress": {
                "host": "target.host.com",
                "port": 1234,
                "scheme": "HTTPS"
            }
        }
    }
}))
require 'mockserver-client'

client = MockServer::Client.new('localhost', 1080)
client.upsert(MockServer::Expectation.from_hash({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "headers": {
                "Host": ["any.host.com"]
            },
            "socketAddress": {
                "host": "target.host.com",
                "port": 1234,
                "scheme": "HTTPS"
            }
        }
    }
}))
package main

import (
    "bytes"
    "net/http"
)

func main() {
    body := []byte(`{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "headers": {
                "Host": ["any.host.com"]
            },
            "socketAddress": {
                "host": "target.host.com",
                "port": 1234,
                "scheme": "HTTPS"
            }
        }
    }
}`)
    req, _ := http.NewRequest("PUT",
        "http://localhost:1080/mockserver/expectation",
        bytes.NewReader(body))
    req.Header.Set("Content-Type", "application/json")
    http.DefaultClient.Do(req)
}
using System.Net.Http;
using System.Text;

using var httpClient = new HttpClient();
var json = @"{
    ""httpRequest"": {
        ""path"": ""/some/path""
    },
    ""httpOverrideForwardedRequest"": {
        ""httpRequest"": {
            ""path"": ""/some/other/path"",
            ""headers"": {
                ""Host"": [""any.host.com""]
            },
            ""socketAddress"": {
                ""host"": ""target.host.com"",
                ""port"": 1234,
                ""scheme"": ""HTTPS""
            }
        }
    }
}";
await httpClient.PutAsync(
    "http://localhost:1080/mockserver/expectation",
    new StringContent(json, Encoding.UTF8, "application/json")
);
use reqwest::blocking::Client;

let client = Client::new();
let body = r#"{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "headers": {
                "Host": ["any.host.com"]
            },
            "socketAddress": {
                "host": "target.host.com",
                "port": 1234,
                "scheme": "HTTPS"
            }
        }
    }
}"#;
client.put("http://localhost:1080/mockserver/expectation")
    .header("Content-Type", "application/json")
    .body(body.to_string())
    .send()
    .unwrap();
$json = <<<'JSON'
{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "headers": {
                "Host": ["any.host.com"]
            },
            "socketAddress": {
                "host": "target.host.com",
                "port": 1234,
                "scheme": "HTTPS"
            }
        }
    }
}
JSON;

$ch = curl_init('http://localhost:1080/mockserver/expectation');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST  => 'PUT',
    CURLOPT_POSTFIELDS     => $json,
    CURLOPT_HTTPHEADER     => ['Content-Type: application/json; charset=utf-8'],
    CURLOPT_RETURNTRANSFER => true,
]);
curl_exec($ch);
curl_close($ch);
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "headers": {
                "Host": ["any.host.com"]
            },
            "socketAddress": {
                "host": "target.host.com",
                "port": 1234,
                "scheme": "HTTPS"
            }
        }
    }
}'

See REST API for full JSON specification

new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .forward(
        forwardOverriddenRequest(
            request()
                .withHeader("Host", "target.host.com")
                .withBody("some_overridden_body")
        ).withDelay(SECONDS, 10)
    );
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "body": "some_overridden_body",
            "headers": {
                "Host": ["target.host.com"]
            }
        },
        "delay": {
            "timeUnit": "SECONDS",
            "value": 10
        }
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);

See REST API for full JSON specification

from mockserver.client import MockServerClient
from mockserver.models import Expectation

client = MockServerClient("localhost", 1080)
client.upsert(Expectation.from_dict({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "body": "some_overridden_body",
            "headers": {
                "Host": ["target.host.com"]
            }
        },
        "delay": {
            "timeUnit": "SECONDS",
            "value": 10
        }
    }
}))
require 'mockserver-client'

client = MockServer::Client.new('localhost', 1080)
client.upsert(MockServer::Expectation.from_hash({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "body": "some_overridden_body",
            "headers": {
                "Host": ["target.host.com"]
            }
        },
        "delay": {
            "timeUnit": "SECONDS",
            "value": 10
        }
    }
}))
package main

import (
    "bytes"
    "net/http"
)

func main() {
    body := []byte(`{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "body": "some_overridden_body",
            "headers": {
                "Host": ["target.host.com"]
            }
        },
        "delay": {
            "timeUnit": "SECONDS",
            "value": 10
        }
    }
}`)
    req, _ := http.NewRequest("PUT",
        "http://localhost:1080/mockserver/expectation",
        bytes.NewReader(body))
    req.Header.Set("Content-Type", "application/json")
    http.DefaultClient.Do(req)
}
using System.Net.Http;
using System.Text;

using var httpClient = new HttpClient();
var json = @"{
    ""httpRequest"": {
        ""path"": ""/some/path""
    },
    ""httpOverrideForwardedRequest"": {
        ""httpRequest"": {
            ""path"": ""/some/other/path"",
            ""body"": ""some_overridden_body"",
            ""headers"": {
                ""Host"": [""target.host.com""]
            }
        },
        ""delay"": {
            ""timeUnit"": ""SECONDS"",
            ""value"": 10
        }
    }
}";
await httpClient.PutAsync(
    "http://localhost:1080/mockserver/expectation",
    new StringContent(json, Encoding.UTF8, "application/json")
);
use reqwest::blocking::Client;

let client = Client::new();
let body = r#"{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "body": "some_overridden_body",
            "headers": {
                "Host": ["target.host.com"]
            }
        },
        "delay": {
            "timeUnit": "SECONDS",
            "value": 10
        }
    }
}"#;
client.put("http://localhost:1080/mockserver/expectation")
    .header("Content-Type", "application/json")
    .body(body.to_string())
    .send()
    .unwrap();
$json = <<<'JSON'
{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "body": "some_overridden_body",
            "headers": {
                "Host": ["target.host.com"]
            }
        },
        "delay": {
            "timeUnit": "SECONDS",
            "value": 10
        }
    }
}
JSON;

$ch = curl_init('http://localhost:1080/mockserver/expectation');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST  => 'PUT',
    CURLOPT_POSTFIELDS     => $json,
    CURLOPT_HTTPHEADER     => ['Content-Type: application/json; charset=utf-8'],
    CURLOPT_RETURNTRANSFER => true,
]);
curl_exec($ch);
curl_close($ch);
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "body": "some_overridden_body",
            "headers": {
                "Host": ["target.host.com"]
            }
        },
        "delay": {
            "timeUnit": "SECONDS",
            "value": 10
        }
    }
}'

See REST API for full JSON specification

Forward actions support the same distribution-based delays as response actions, allowing realistic latency simulation when proxying requests.

new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .forward(
        forwardOverriddenRequest(
            request()
                .withHeader("Host", "target.host.com")
                .withBody("some_overridden_body")
        ).withDelay(Delay.logNormal(TimeUnit.MILLISECONDS, 200, 800))
    );
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "body": "some_overridden_body",
            "headers": {
                "Host": ["target.host.com"]
            }
        },
        "delay": {
            "timeUnit": "MILLISECONDS",
            "distribution": {
                "type": "LOG_NORMAL",
                "median": 200,
                "p99": 800
            }
        }
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);

See REST API for full JSON specification

from mockserver.client import MockServerClient
from mockserver.models import Expectation

client = MockServerClient("localhost", 1080)
client.upsert(Expectation.from_dict({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "body": "some_overridden_body",
            "headers": {
                "Host": ["target.host.com"]
            }
        },
        "delay": {
            "timeUnit": "MILLISECONDS",
            "distribution": {
                "type": "LOG_NORMAL",
                "median": 200,
                "p99": 800
            }
        }
    }
}))
require 'mockserver-client'

client = MockServer::Client.new('localhost', 1080)
client.upsert(MockServer::Expectation.from_hash({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "body": "some_overridden_body",
            "headers": {
                "Host": ["target.host.com"]
            }
        },
        "delay": {
            "timeUnit": "MILLISECONDS",
            "distribution": {
                "type": "LOG_NORMAL",
                "median": 200,
                "p99": 800
            }
        }
    }
}))
package main

import (
    "bytes"
    "net/http"
)

func main() {
    body := []byte(`{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "body": "some_overridden_body",
            "headers": {
                "Host": ["target.host.com"]
            }
        },
        "delay": {
            "timeUnit": "MILLISECONDS",
            "distribution": {
                "type": "LOG_NORMAL",
                "median": 200,
                "p99": 800
            }
        }
    }
}`)
    req, _ := http.NewRequest("PUT",
        "http://localhost:1080/mockserver/expectation",
        bytes.NewReader(body))
    req.Header.Set("Content-Type", "application/json")
    http.DefaultClient.Do(req)
}
using System.Net.Http;
using System.Text;

using var httpClient = new HttpClient();
var json = @"{
    ""httpRequest"": {
        ""path"": ""/some/path""
    },
    ""httpOverrideForwardedRequest"": {
        ""httpRequest"": {
            ""path"": ""/some/other/path"",
            ""body"": ""some_overridden_body"",
            ""headers"": {
                ""Host"": [""target.host.com""]
            }
        },
        ""delay"": {
            ""timeUnit"": ""MILLISECONDS"",
            ""distribution"": {
                ""type"": ""LOG_NORMAL"",
                ""median"": 200,
                ""p99"": 800
            }
        }
    }
}";
await httpClient.PutAsync(
    "http://localhost:1080/mockserver/expectation",
    new StringContent(json, Encoding.UTF8, "application/json")
);
use reqwest::blocking::Client;

let client = Client::new();
let body = r#"{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "body": "some_overridden_body",
            "headers": {
                "Host": ["target.host.com"]
            }
        },
        "delay": {
            "timeUnit": "MILLISECONDS",
            "distribution": {
                "type": "LOG_NORMAL",
                "median": 200,
                "p99": 800
            }
        }
    }
}"#;
client.put("http://localhost:1080/mockserver/expectation")
    .header("Content-Type", "application/json")
    .body(body.to_string())
    .send()
    .unwrap();
$json = <<<'JSON'
{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "body": "some_overridden_body",
            "headers": {
                "Host": ["target.host.com"]
            }
        },
        "delay": {
            "timeUnit": "MILLISECONDS",
            "distribution": {
                "type": "LOG_NORMAL",
                "median": 200,
                "p99": 800
            }
        }
    }
}
JSON;

$ch = curl_init('http://localhost:1080/mockserver/expectation');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST  => 'PUT',
    CURLOPT_POSTFIELDS     => $json,
    CURLOPT_HTTPHEADER     => ['Content-Type: application/json; charset=utf-8'],
    CURLOPT_RETURNTRANSFER => true,
]);
curl_exec($ch);
curl_close($ch);
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "httpRequest": {
            "path": "/some/other/path",
            "body": "some_overridden_body",
            "headers": {
                "Host": ["target.host.com"]
            }
        },
        "delay": {
            "timeUnit": "MILLISECONDS",
            "distribution": {
                "type": "LOG_NORMAL",
                "median": 200,
                "p99": 800
            }
        }
    }
}'

See REST API for full JSON specification

// request.queryStringParameters['userId'] returns an array of values because headers and queryStringParameters have multiple values
String template = "return {\n" +
    "    'path' : \"/somePath\",\n" +
    "    'queryStringParameters' : {\n" +
    "        'userId' : request.queryStringParameters && request.queryStringParameters['userId']\n" +
    "    },\n" +
    "    'headers' : {\n" +
    "        'Host' : [ \"localhost:1081\" ]\n" +
    "    },\n" +
    "    'body': JSON.stringify({'name': 'value'})\n" +
    "};";

new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .forward(
        template(
            HttpTemplate.TemplateType.JAVASCRIPT,
            template
        )
    );
var mockServerClient = require('mockserver-client').mockServerClient;
// request.queryStringParameters['userId'] returns an array of values because headers and queryStringParameters have multiple values
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForwardTemplate": {
        "template": "return {\n" +
        "    'path' : \"/somePath\",\n" +
        "    'queryStringParameters' : {\n" +
        "        'userId' : request.queryStringParameters && request.queryStringParameters['userId']\n" +
        "    },\n" +
        "    'headers' : {\n" +
        "        'Host' : [ \"localhost:1081\" ]\n" +
        "    },\n" +
        "    'body': JSON.stringify({'name': 'value'})\n" +
        "};",
        "templateType": "JAVASCRIPT"
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);

See REST API for full JSON specification

from mockserver.client import MockServerClient
from mockserver.models import Expectation

client = MockServerClient("localhost", 1080)
client.upsert(Expectation.from_dict({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForwardTemplate": {
        "template": "return {\n" +
        "    'path' : \"/somePath\",\n" +
        "    'queryStringParameters' : {\n" +
        "        'userId' : request.queryStringParameters && request.queryStringParameters['userId']\n" +
        "    },\n" +
        "    'headers' : {\n" +
        "        'Host' : [ \"localhost:1081\" ]\n" +
        "    },\n" +
        "    'body': JSON.stringify({'name': 'value'})\n" +
        "};",
        "templateType": "JAVASCRIPT"
    }
}))
require 'mockserver-client'

client = MockServer::Client.new('localhost', 1080)
client.upsert(MockServer::Expectation.from_hash({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForwardTemplate": {
        "template": "return {\n" +
        "    'path' : \"/somePath\",\n" +
        "    'queryStringParameters' : {\n" +
        "        'userId' : request.queryStringParameters && request.queryStringParameters['userId']\n" +
        "    },\n" +
        "    'headers' : {\n" +
        "        'Host' : [ \"localhost:1081\" ]\n" +
        "    },\n" +
        "    'body': JSON.stringify({'name': 'value'})\n" +
        "};",
        "templateType": "JAVASCRIPT"
    }
}))
package main

import (
    "bytes"
    "net/http"
)

func main() {
    body := []byte(`{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForwardTemplate": {
        "template": "return {\n" +
        "    'path' : \"/somePath\",\n" +
        "    'queryStringParameters' : {\n" +
        "        'userId' : request.queryStringParameters && request.queryStringParameters['userId']\n" +
        "    },\n" +
        "    'headers' : {\n" +
        "        'Host' : [ \"localhost:1081\" ]\n" +
        "    },\n" +
        "    'body': JSON.stringify({'name': 'value'})\n" +
        "};",
        "templateType": "JAVASCRIPT"
    }
}`)
    req, _ := http.NewRequest("PUT",
        "http://localhost:1080/mockserver/expectation",
        bytes.NewReader(body))
    req.Header.Set("Content-Type", "application/json")
    http.DefaultClient.Do(req)
}
using System.Net.Http;
using System.Text;

using var httpClient = new HttpClient();
var json = @"{
    ""httpRequest"": {
        ""path"": ""/some/path""
    },
    ""httpForwardTemplate"": {
        ""template"": ""return {\n"" +
        ""    'path' : \""/somePath\"",\n"" +
        ""    'queryStringParameters' : {\n"" +
        ""        'userId' : request.queryStringParameters && request.queryStringParameters['userId']\n"" +
        ""    },\n"" +
        ""    'headers' : {\n"" +
        ""        'Host' : [ \""localhost:1081\"" ]\n"" +
        ""    },\n"" +
        ""    'body': JSON.stringify({'name': 'value'})\n"" +
        ""};"",
        ""templateType"": ""JAVASCRIPT""
    }
}";
await httpClient.PutAsync(
    "http://localhost:1080/mockserver/expectation",
    new StringContent(json, Encoding.UTF8, "application/json")
);
use reqwest::blocking::Client;

let client = Client::new();
let body = r#"{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForwardTemplate": {
        "template": "return {\n" +
        "    'path' : \"/somePath\",\n" +
        "    'queryStringParameters' : {\n" +
        "        'userId' : request.queryStringParameters && request.queryStringParameters['userId']\n" +
        "    },\n" +
        "    'headers' : {\n" +
        "        'Host' : [ \"localhost:1081\" ]\n" +
        "    },\n" +
        "    'body': JSON.stringify({'name': 'value'})\n" +
        "};",
        "templateType": "JAVASCRIPT"
    }
}"#;
client.put("http://localhost:1080/mockserver/expectation")
    .header("Content-Type", "application/json")
    .body(body.to_string())
    .send()
    .unwrap();
$json = <<<'JSON'
{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForwardTemplate": {
        "template": "return {\n" +
        "    'path' : \"/somePath\",\n" +
        "    'queryStringParameters' : {\n" +
        "        'userId' : request.queryStringParameters && request.queryStringParameters['userId']\n" +
        "    },\n" +
        "    'headers' : {\n" +
        "        'Host' : [ \"localhost:1081\" ]\n" +
        "    },\n" +
        "    'body': JSON.stringify({'name': 'value'})\n" +
        "};",
        "templateType": "JAVASCRIPT"
    }
}
JSON;

$ch = curl_init('http://localhost:1080/mockserver/expectation');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST  => 'PUT',
    CURLOPT_POSTFIELDS     => $json,
    CURLOPT_HTTPHEADER     => ['Content-Type: application/json; charset=utf-8'],
    CURLOPT_RETURNTRANSFER => true,
]);
curl_exec($ch);
curl_close($ch);
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForwardTemplate": {
        "template": "return {\n" +
        "    'path' : \"/somePath\",\n" +
        "    'queryStringParameters' : {\n" +
        "        'userId' : request.queryStringParameters && request.queryStringParameters['userId']\n" +
        "    },\n" +
        "    'headers' : {\n" +
        "        'Host' : [ \"localhost:1081\" ]\n" +
        "    },\n" +
        "    'body': JSON.stringify({'name': 'value'})\n" +
        "};",
        "templateType": "JAVASCRIPT"
    }
}'

See REST API for full JSON specification

String template = "return {" + System.getProperty("line.separator") +
    "    'path' : request.path.substring(request.path.indexOf('/somePrefix')+'/somePrefix'.length,request.path.length)," + System.getProperty("line.separator") +
    "    'headers' : {" + System.getProperty("line.separator") +
    "        'Host' : [ \"localhost:1081\" ]" + System.getProperty("line.separator") +
    "    }," + System.getProperty("line.separator") +
    "};";

new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/somePrefix*")
    )
    .forward(
        template(
            HttpTemplate.TemplateType.JAVASCRIPT,
            template
        )
    );
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "path": "/somePrefix*"
    },
    "httpForwardTemplate": {
        "template": "return {\n" +
        "    'path' : request.path.substring(request.path.indexOf('/somePrefix')+'/somePrefix'.length,request.path.length),\n" +
        "    'headers' : {\n" +
        "        'Host' : [ \"localhost:1081\" ]\n" +
        "    }
        "};",
        "templateType": "JAVASCRIPT"
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);

See REST API for full JSON specification

from mockserver.client import MockServerClient
from mockserver.models import Expectation

client = MockServerClient("localhost", 1080)
client.upsert(Expectation.from_dict({
    "httpRequest": {
        "path": "/somePrefix*"
    },
    "httpForwardTemplate": {
        "template": "return {\n" +
        "    'path' : request.path.substring(request.path.indexOf('/somePrefix')+'/somePrefix'.length,request.path.length),\n" +
        "    'headers' : {\n" +
        "        'Host' : [ \"localhost:1081\" ]\n" +
        "    }\n" +
        "};",
        "templateType": "JAVASCRIPT"
    }
}))
require 'mockserver-client'

client = MockServer::Client.new('localhost', 1080)
client.upsert(MockServer::Expectation.from_hash({
    "httpRequest": {
        "path": "/somePrefix*"
    },
    "httpForwardTemplate": {
        "template": "return {\n" +
        "    'path' : request.path.substring(request.path.indexOf('/somePrefix')+'/somePrefix'.length,request.path.length),\n" +
        "    'headers' : {\n" +
        "        'Host' : [ \"localhost:1081\" ]\n" +
        "    }\n" +
        "};",
        "templateType": "JAVASCRIPT"
    }
}))
package main

import (
    "bytes"
    "net/http"
)

func main() {
    body := []byte(`{
    "httpRequest": {
        "path": "/somePrefix*"
    },
    "httpForwardTemplate": {
        "template": "return {\n" +
        "    'path' : request.path.substring(request.path.indexOf('/somePrefix')+'/somePrefix'.length,request.path.length),\n" +
        "    'headers' : {\n" +
        "        'Host' : [ \"localhost:1081\" ]\n" +
        "    }\n" +
        "};",
        "templateType": "JAVASCRIPT"
    }
}`)
    req, _ := http.NewRequest("PUT",
        "http://localhost:1080/mockserver/expectation",
        bytes.NewReader(body))
    req.Header.Set("Content-Type", "application/json")
    http.DefaultClient.Do(req)
}
using System.Net.Http;
using System.Text;

using var httpClient = new HttpClient();
var json = @"{
    ""httpRequest"": {
        ""path"": ""/somePrefix*""
    },
    ""httpForwardTemplate"": {
        ""template"": ""return {\n"" +
        ""    'path' : request.path.substring(request.path.indexOf('/somePrefix')+'/somePrefix'.length,request.path.length),\n"" +
        ""    'headers' : {\n"" +
        ""        'Host' : [ \""localhost:1081\"" ]\n"" +
        ""    }\n"" +
        ""};"",
        ""templateType"": ""JAVASCRIPT""
    }
}";
await httpClient.PutAsync(
    "http://localhost:1080/mockserver/expectation",
    new StringContent(json, Encoding.UTF8, "application/json")
);
use reqwest::blocking::Client;

let client = Client::new();
let body = r#"{
    "httpRequest": {
        "path": "/somePrefix*"
    },
    "httpForwardTemplate": {
        "template": "return {\n" +
        "    'path' : request.path.substring(request.path.indexOf('/somePrefix')+'/somePrefix'.length,request.path.length),\n" +
        "    'headers' : {\n" +
        "        'Host' : [ \"localhost:1081\" ]\n" +
        "    }\n" +
        "};",
        "templateType": "JAVASCRIPT"
    }
}"#;
client.put("http://localhost:1080/mockserver/expectation")
    .header("Content-Type", "application/json")
    .body(body.to_string())
    .send()
    .unwrap();
$json = <<<'JSON'
{
    "httpRequest": {
        "path": "/somePrefix*"
    },
    "httpForwardTemplate": {
        "template": "return {\n" +
        "    'path' : request.path.substring(request.path.indexOf('/somePrefix')+'/somePrefix'.length,request.path.length),\n" +
        "    'headers' : {\n" +
        "        'Host' : [ \"localhost:1081\" ]\n" +
        "    }\n" +
        "};",
        "templateType": "JAVASCRIPT"
    }
}
JSON;

$ch = curl_init('http://localhost:1080/mockserver/expectation');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST  => 'PUT',
    CURLOPT_POSTFIELDS     => $json,
    CURLOPT_HTTPHEADER     => ['Content-Type: application/json; charset=utf-8'],
    CURLOPT_RETURNTRANSFER => true,
]);
curl_exec($ch);
curl_close($ch);
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
        "path": "/somePrefix*"
    },
    "httpForwardTemplate": {
        "template": "return {\n" +
        "    'path' : request.path.substring(request.path.indexOf('/somePrefix')+'/somePrefix'.length,request.path.length),\n" +
        "    'headers' : {\n" +
        "        'Host' : [ \"localhost:1081\" ]\n" +
        "    }\n" +
        "};",
        "templateType": "JAVASCRIPT"
    }
}'

See REST API for full JSON specification

// request.cookies['SessionId'] returns a single value because cookies only contain a single value
String template = "return {\n" +
    "    'path' : \"/somePath\",\n" +
    "    'cookies' : {\n" +
    "        'SessionId' : request.cookies && request.cookies['SessionId']\n" +
    "    },\n" +
    "    'headers' : {\n" +
    "        'Host' : [ \"localhost:1081\" ]\n" +
    "    },\n" +
    "    'keepAlive' : true,\n" +
    "    'secure' : true,\n" +
    "    'body' : \"some_body\"\n" +
    "};";

new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .forward(
        template(HttpTemplate.TemplateType.JAVASCRIPT)
            .withTemplate(template)
            .withDelay(TimeUnit.SECONDS, 20)
    );
var mockServerClient = require('mockserver-client').mockServerClient;
// request.cookies['SessionId'] returns a single value because cookies only contain a single value
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForwardTemplate": {
        "template": "return {\n" +
        "    'path' : \"/somePath\",\n" +
        "    'cookies' : {\n" +
        "        'SessionId' : request.cookies && request.cookies['SessionId']\n" +
        "    },\n" +
        "    'headers' : {\n" +
        "        'Host' : [ \"localhost:1081\" ]\n" +
        "    },\n" +
        "    'keepAlive' : true,\n" +
        "    'secure' : true,\n" +
        "    'body' : \"some_body\"\n" +
        "};",
        "templateType": "JAVASCRIPT",
        "delay": {"timeUnit": "SECONDS", "value": 20}
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);

See REST API for full JSON specification

from mockserver.client import MockServerClient
from mockserver.models import Expectation

client = MockServerClient("localhost", 1080)
client.upsert(Expectation.from_dict({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForwardTemplate": {
        "template": "return {\n" +
        "    'path' : \"/somePath\",\n" +
        "    'cookies' : {\n" +
        "        'SessionId' : request.cookies && request.cookies['SessionId']\n" +
        "    },\n" +
        "    'headers' : {\n" +
        "        'Host' : [ \"localhost:1081\" ]\n" +
        "    },\n" +
        "    'keepAlive' : True,\n" +
        "    'secure' : True,\n" +
        "    'body' : \"some_body\"\n" +
        "};",
        "templateType": "JAVASCRIPT",
        "delay": {"timeUnit": "SECONDS", "value": 20}
    }
}))
require 'mockserver-client'

client = MockServer::Client.new('localhost', 1080)
client.upsert(MockServer::Expectation.from_hash({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForwardTemplate": {
        "template": "return {\n" +
        "    'path' : \"/somePath\",\n" +
        "    'cookies' : {\n" +
        "        'SessionId' : request.cookies && request.cookies['SessionId']\n" +
        "    },\n" +
        "    'headers' : {\n" +
        "        'Host' : [ \"localhost:1081\" ]\n" +
        "    },\n" +
        "    'keepAlive' : true,\n" +
        "    'secure' : true,\n" +
        "    'body' : \"some_body\"\n" +
        "};",
        "templateType": "JAVASCRIPT",
        "delay": {"timeUnit": "SECONDS", "value": 20}
    }
}))
package main

import (
    "bytes"
    "net/http"
)

func main() {
    body := []byte(`{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForwardTemplate": {
        "template": "return {\n" +
        "    'path' : \"/somePath\",\n" +
        "    'cookies' : {\n" +
        "        'SessionId' : request.cookies && request.cookies['SessionId']\n" +
        "    },\n" +
        "    'headers' : {\n" +
        "        'Host' : [ \"localhost:1081\" ]\n" +
        "    },\n" +
        "    'keepAlive' : true,\n" +
        "    'secure' : true,\n" +
        "    'body' : \"some_body\"\n" +
        "};",
        "templateType": "JAVASCRIPT",
        "delay": {"timeUnit": "SECONDS", "value": 20}
    }
}`)
    req, _ := http.NewRequest("PUT",
        "http://localhost:1080/mockserver/expectation",
        bytes.NewReader(body))
    req.Header.Set("Content-Type", "application/json")
    http.DefaultClient.Do(req)
}
using System.Net.Http;
using System.Text;

using var httpClient = new HttpClient();
var json = @"{
    ""httpRequest"": {
        ""path"": ""/some/path""
    },
    ""httpForwardTemplate"": {
        ""template"": ""return {\n"" +
        ""    'path' : \""/somePath\"",\n"" +
        ""    'cookies' : {\n"" +
        ""        'SessionId' : request.cookies && request.cookies['SessionId']\n"" +
        ""    },\n"" +
        ""    'headers' : {\n"" +
        ""        'Host' : [ \""localhost:1081\"" ]\n"" +
        ""    },\n"" +
        ""    'keepAlive' : true,\n"" +
        ""    'secure' : true,\n"" +
        ""    'body' : \""some_body\""\n"" +
        ""};"",
        ""templateType"": ""JAVASCRIPT"",
        ""delay"": {""timeUnit"": ""SECONDS"", ""value"": 20}
    }
}";
await httpClient.PutAsync(
    "http://localhost:1080/mockserver/expectation",
    new StringContent(json, Encoding.UTF8, "application/json")
);
use reqwest::blocking::Client;

let client = Client::new();
let body = r#"{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForwardTemplate": {
        "template": "return {\n" +
        "    'path' : \"/somePath\",\n" +
        "    'cookies' : {\n" +
        "        'SessionId' : request.cookies && request.cookies['SessionId']\n" +
        "    },\n" +
        "    'headers' : {\n" +
        "        'Host' : [ \"localhost:1081\" ]\n" +
        "    },\n" +
        "    'keepAlive' : true,\n" +
        "    'secure' : true,\n" +
        "    'body' : \"some_body\"\n" +
        "};",
        "templateType": "JAVASCRIPT",
        "delay": {"timeUnit": "SECONDS", "value": 20}
    }
}"#;
client.put("http://localhost:1080/mockserver/expectation")
    .header("Content-Type", "application/json")
    .body(body.to_string())
    .send()
    .unwrap();
$json = <<<'JSON'
{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForwardTemplate": {
        "template": "return {\n" +
        "    'path' : \"/somePath\",\n" +
        "    'cookies' : {\n" +
        "        'SessionId' : request.cookies && request.cookies['SessionId']\n" +
        "    },\n" +
        "    'headers' : {\n" +
        "        'Host' : [ \"localhost:1081\" ]\n" +
        "    },\n" +
        "    'keepAlive' : true,\n" +
        "    'secure' : true,\n" +
        "    'body' : \"some_body\"\n" +
        "};",
        "templateType": "JAVASCRIPT",
        "delay": {"timeUnit": "SECONDS", "value": 20}
    }
}
JSON;

$ch = curl_init('http://localhost:1080/mockserver/expectation');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST  => 'PUT',
    CURLOPT_POSTFIELDS     => $json,
    CURLOPT_HTTPHEADER     => ['Content-Type: application/json; charset=utf-8'],
    CURLOPT_RETURNTRANSFER => true,
]);
curl_exec($ch);
curl_close($ch);
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForwardTemplate": {
        "template": "return {\n" +
        "    'path' : \"/somePath\",\n" +
        "    'cookies' : {\n" +
        "        'SessionId' : request.cookies && request.cookies['SessionId']\n" +
        "    },\n" +
        "    'headers' : {\n" +
        "        'Host' : [ \"localhost:1081\" ]\n" +
        "    },\n" +
        "    'keepAlive' : true,\n" +
        "    'secure' : true,\n" +
        "    'body' : \"some_body\"\n" +
        "};",
        "templateType": "JAVASCRIPT",
        "delay": {"timeUnit": "SECONDS", "value": 20}
    }
}'

See REST API for full JSON specification

// $!request.queryStringParameters['userId'] returns an array of values because headers and queryStringParameters have multiple values
String template = "{\n" +
    "    'path' : \"/somePath\",\n" +
    "    'queryStringParameters' : {\n" +
    "        'userId' : [ \"$!request.queryStringParameters['userId'][0]\" ]\n" +
    "    },\n" +
    "    'cookies' : {\n" +
    "        'SessionId' : \"$!request.cookies['SessionId']\"\n" +
    "    },\n" +
    "    'headers' : {\n" +
    "        'Host' : [ \"localhost:1081\" ]\n" +
    "    },\n" +
    "    'body': \"{'name': 'value'}\"\n" +
    "}";

new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .forward(
        template(
            HttpTemplate.TemplateType.VELOCITY,
            template
        )
    );
var mockServerClient = require('mockserver-client').mockServerClient;
// $!request.queryStringParameters['userId'] returns an array of values because headers and queryStringParameters have multiple values
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForwardTemplate": {
        "template": "{\n" +
        "    'path' : \"/somePath\",\n" +
        "    'queryStringParameters' : {\n" +
        "        'userId' : [ \"$!request.queryStringParameters['userId'][0]\" ]\n" +
        "    },\n" +
        "    'cookies' : {\n" +
        "        'SessionId' : \"$!request.cookies['SessionId']\"\n" +
        "    },\n" +
        "    'headers' : {\n" +
        "        'Host' : [ \"localhost:1081\" ]\n" +
        "    },\n" +
        "    'body': \"{'name': 'value'}\"\n" +
        "}",
        "templateType": "VELOCITY"
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);

See REST API for full JSON specification

from mockserver.client import MockServerClient
from mockserver.models import Expectation

client = MockServerClient("localhost", 1080)
client.upsert(Expectation.from_dict({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForwardTemplate": {
        "template": "{\n" +
        "    'path' : \"/somePath\",\n" +
        "    'queryStringParameters' : {\n" +
        "        'userId' : [ \"$!request.queryStringParameters['userId'][0]\" ]\n" +
        "    },\n" +
        "    'cookies' : {\n" +
        "        'SessionId' : \"$!request.cookies['SessionId']\"\n" +
        "    },\n" +
        "    'headers' : {\n" +
        "        'Host' : [ \"localhost:1081\" ]\n" +
        "    },\n" +
        "    'body': \"{'name': 'value'}\"\n" +
        "}",
        "templateType": "VELOCITY"
    }
}))
require 'mockserver-client'

client = MockServer::Client.new('localhost', 1080)
client.upsert(MockServer::Expectation.from_hash({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForwardTemplate": {
        "template": "{\n" +
        "    'path' : \"/somePath\",\n" +
        "    'queryStringParameters' : {\n" +
        "        'userId' : [ \"$!request.queryStringParameters['userId'][0]\" ]\n" +
        "    },\n" +
        "    'cookies' : {\n" +
        "        'SessionId' : \"$!request.cookies['SessionId']\"\n" +
        "    },\n" +
        "    'headers' : {\n" +
        "        'Host' : [ \"localhost:1081\" ]\n" +
        "    },\n" +
        "    'body': \"{'name': 'value'}\"\n" +
        "}",
        "templateType": "VELOCITY"
    }
}))
package main

import (
    "bytes"
    "net/http"
)

func main() {
    body := []byte(`{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForwardTemplate": {
        "template": "{\n" +
        "    'path' : \"/somePath\",\n" +
        "    'queryStringParameters' : {\n" +
        "        'userId' : [ \"$!request.queryStringParameters['userId'][0]\" ]\n" +
        "    },\n" +
        "    'cookies' : {\n" +
        "        'SessionId' : \"$!request.cookies['SessionId']\"\n" +
        "    },\n" +
        "    'headers' : {\n" +
        "        'Host' : [ \"localhost:1081\" ]\n" +
        "    },\n" +
        "    'body': \"{'name': 'value'}\"\n" +
        "}",
        "templateType": "VELOCITY"
    }
}`)
    req, _ := http.NewRequest("PUT",
        "http://localhost:1080/mockserver/expectation",
        bytes.NewReader(body))
    req.Header.Set("Content-Type", "application/json")
    http.DefaultClient.Do(req)
}
using System.Net.Http;
using System.Text;

using var httpClient = new HttpClient();
var json = @"{
    ""httpRequest"": {
        ""path"": ""/some/path""
    },
    ""httpForwardTemplate"": {
        ""template"": ""{\n"" +
        ""    'path' : \""/somePath\"",\n"" +
        ""    'queryStringParameters' : {\n"" +
        ""        'userId' : [ \""$!request.queryStringParameters['userId'][0]\"" ]\n"" +
        ""    },\n"" +
        ""    'cookies' : {\n"" +
        ""        'SessionId' : \""$!request.cookies['SessionId']\""\n"" +
        ""    },\n"" +
        ""    'headers' : {\n"" +
        ""        'Host' : [ \""localhost:1081\"" ]\n"" +
        ""    },\n"" +
        ""    'body': \""{'name': 'value'}\""\n"" +
        ""}"",
        ""templateType"": ""VELOCITY""
    }
}";
await httpClient.PutAsync(
    "http://localhost:1080/mockserver/expectation",
    new StringContent(json, Encoding.UTF8, "application/json")
);
use reqwest::blocking::Client;

let client = Client::new();
let body = r#"{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForwardTemplate": {
        "template": "{\n" +
        "    'path' : \"/somePath\",\n" +
        "    'queryStringParameters' : {\n" +
        "        'userId' : [ \"$!request.queryStringParameters['userId'][0]\" ]\n" +
        "    },\n" +
        "    'cookies' : {\n" +
        "        'SessionId' : \"$!request.cookies['SessionId']\"\n" +
        "    },\n" +
        "    'headers' : {\n" +
        "        'Host' : [ \"localhost:1081\" ]\n" +
        "    },\n" +
        "    'body': \"{'name': 'value'}\"\n" +
        "}",
        "templateType": "VELOCITY"
    }
}"#;
client.put("http://localhost:1080/mockserver/expectation")
    .header("Content-Type", "application/json")
    .body(body.to_string())
    .send()
    .unwrap();
$json = <<<'JSON'
{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForwardTemplate": {
        "template": "{\n" +
        "    'path' : \"/somePath\",\n" +
        "    'queryStringParameters' : {\n" +
        "        'userId' : [ \"$!request.queryStringParameters['userId'][0]\" ]\n" +
        "    },\n" +
        "    'cookies' : {\n" +
        "        'SessionId' : \"$!request.cookies['SessionId']\"\n" +
        "    },\n" +
        "    'headers' : {\n" +
        "        'Host' : [ \"localhost:1081\" ]\n" +
        "    },\n" +
        "    'body': \"{'name': 'value'}\"\n" +
        "}",
        "templateType": "VELOCITY"
    }
}
JSON;

$ch = curl_init('http://localhost:1080/mockserver/expectation');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST  => 'PUT',
    CURLOPT_POSTFIELDS     => $json,
    CURLOPT_HTTPHEADER     => ['Content-Type: application/json; charset=utf-8'],
    CURLOPT_RETURNTRANSFER => true,
]);
curl_exec($ch);
curl_close($ch);
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForwardTemplate": {
        "template": "{\n" +
        "    'path' : \"/somePath\",\n" +
        "    'queryStringParameters' : {\n" +
        "        'userId' : [ \"$!request.queryStringParameters['userId'][0]\" ]\n" +
        "    },\n" +
        "    'cookies' : {\n" +
        "        'SessionId' : \"$!request.cookies['SessionId']\"\n" +
        "    },\n" +
        "    'headers' : {\n" +
        "        'Host' : [ \"localhost:1081\" ]\n" +
        "    },\n" +
        "    'body': \"{'name': 'value'}\"\n" +
        "}",
        "templateType": "VELOCITY"
    }
}'

See REST API for full JSON specification

A response template allows you to transform the response returned from the upstream server using a template that has access to both the original request and the upstream response. This is useful when you need to dynamically modify responses based on request context — for example, injecting request headers into the response body or conditionally changing the status code.

The template receives two objects: request (the original request) and response (the upstream response). The template must return a valid HTTP response JSON object.

new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .forward(
        forwardOverriddenRequest(
            request()
                .withHeader("Host", "target.host.com")
        )
        .withResponseTemplate(
            template(
                HttpTemplate.TemplateType.JAVASCRIPT,
                "return { 'statusCode': response.statusCode, 'headers': response.headers, 'body': JSON.stringify({ 'originalBody': response.body, 'requestPath': request.path }) };"
            )
        )
    );
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "requestOverride": {
            "headers": {
                "Host": ["target.host.com"]
            }
        },
        "responseTemplate": {
            "templateType": "JAVASCRIPT",
            "template": "return { 'statusCode': response.statusCode, 'headers': response.headers, 'body': JSON.stringify({ 'originalBody': response.body, 'requestPath': request.path }) };"
        }
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);

See REST API for full JSON specification

from mockserver.client import MockServerClient
from mockserver.models import Expectation

client = MockServerClient("localhost", 1080)
client.upsert(Expectation.from_dict({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "requestOverride": {
            "headers": {
                "Host": ["target.host.com"]
            }
        },
        "responseTemplate": {
            "templateType": "JAVASCRIPT",
            "template": "return { 'statusCode': response.statusCode, 'headers': response.headers, 'body': JSON.stringify({ 'originalBody': response.body, 'requestPath': request.path }) };"
        }
    }
}))
require 'mockserver-client'

client = MockServer::Client.new('localhost', 1080)
client.upsert(MockServer::Expectation.from_hash({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "requestOverride": {
            "headers": {
                "Host": ["target.host.com"]
            }
        },
        "responseTemplate": {
            "templateType": "JAVASCRIPT",
            "template": "return { 'statusCode': response.statusCode, 'headers': response.headers, 'body': JSON.stringify({ 'originalBody': response.body, 'requestPath': request.path }) };"
        }
    }
}))
package main

import (
    "bytes"
    "net/http"
)

func main() {
    body := []byte(`{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "requestOverride": {
            "headers": {
                "Host": ["target.host.com"]
            }
        },
        "responseTemplate": {
            "templateType": "JAVASCRIPT",
            "template": "return { 'statusCode': response.statusCode, 'headers': response.headers, 'body': JSON.stringify({ 'originalBody': response.body, 'requestPath': request.path }) };"
        }
    }
}`)
    req, _ := http.NewRequest("PUT",
        "http://localhost:1080/mockserver/expectation",
        bytes.NewReader(body))
    req.Header.Set("Content-Type", "application/json")
    http.DefaultClient.Do(req)
}
using System.Net.Http;
using System.Text;

using var httpClient = new HttpClient();
var json = @"{
    ""httpRequest"": {
        ""path"": ""/some/path""
    },
    ""httpOverrideForwardedRequest"": {
        ""requestOverride"": {
            ""headers"": {
                ""Host"": [""target.host.com""]
            }
        },
        ""responseTemplate"": {
            ""templateType"": ""JAVASCRIPT"",
            ""template"": ""return { 'statusCode': response.statusCode, 'headers': response.headers, 'body': JSON.stringify({ 'originalBody': response.body, 'requestPath': request.path }) };""
        }
    }
}";
await httpClient.PutAsync(
    "http://localhost:1080/mockserver/expectation",
    new StringContent(json, Encoding.UTF8, "application/json")
);
use reqwest::blocking::Client;

let client = Client::new();
let body = r#"{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "requestOverride": {
            "headers": {
                "Host": ["target.host.com"]
            }
        },
        "responseTemplate": {
            "templateType": "JAVASCRIPT",
            "template": "return { 'statusCode': response.statusCode, 'headers': response.headers, 'body': JSON.stringify({ 'originalBody': response.body, 'requestPath': request.path }) };"
        }
    }
}"#;
client.put("http://localhost:1080/mockserver/expectation")
    .header("Content-Type", "application/json")
    .body(body.to_string())
    .send()
    .unwrap();
$json = <<<'JSON'
{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "requestOverride": {
            "headers": {
                "Host": ["target.host.com"]
            }
        },
        "responseTemplate": {
            "templateType": "JAVASCRIPT",
            "template": "return { 'statusCode': response.statusCode, 'headers': response.headers, 'body': JSON.stringify({ 'originalBody': response.body, 'requestPath': request.path }) };"
        }
    }
}
JSON;

$ch = curl_init('http://localhost:1080/mockserver/expectation');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST  => 'PUT',
    CURLOPT_POSTFIELDS     => $json,
    CURLOPT_HTTPHEADER     => ['Content-Type: application/json; charset=utf-8'],
    CURLOPT_RETURNTRANSFER => true,
]);
curl_exec($ch);
curl_close($ch);
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpOverrideForwardedRequest": {
        "requestOverride": {
            "headers": {
                "Host": ["target.host.com"]
            }
        },
        "responseTemplate": {
            "templateType": "JAVASCRIPT",
            "template": "return { 'statusCode': response.statusCode, 'headers': response.headers, 'body': JSON.stringify({ 'originalBody': response.body, 'requestPath': request.path }) };"
        }
    }
}'

See REST API for full JSON specification

When using a templated forward (JavaScript, Velocity, or Mustache), you can also specify a responseOverride and/or responseModifier to statically modify the response returned from the upstream server — without needing a separate response template.

new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .forward(
        template(
            HttpTemplate.TemplateType.JAVASCRIPT,
            "return { 'path': '/target' + request.path, 'headers': { 'Host': ['target.host.com'] } };"
        )
        .withResponseOverride(
            response()
                .withHeader("x-proxy", "mockserver")
        )
    );
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForwardTemplate": {
        "templateType": "JAVASCRIPT",
        "template": "return { 'path': '/target' + request.path, 'headers': { 'Host': ['target.host.com'] } };",
        "responseOverride": {
            "headers": {
                "x-proxy": ["mockserver"]
            }
        }
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);

See REST API for full JSON specification

from mockserver.client import MockServerClient
from mockserver.models import Expectation

client = MockServerClient("localhost", 1080)
client.upsert(Expectation.from_dict({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForwardTemplate": {
        "templateType": "JAVASCRIPT",
        "template": "return { 'path': '/target' + request.path, 'headers': { 'Host': ['target.host.com'] } };",
        "responseOverride": {
            "headers": {
                "x-proxy": ["mockserver"]
            }
        }
    }
}))
require 'mockserver-client'

client = MockServer::Client.new('localhost', 1080)
client.upsert(MockServer::Expectation.from_hash({
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForwardTemplate": {
        "templateType": "JAVASCRIPT",
        "template": "return { 'path': '/target' + request.path, 'headers': { 'Host': ['target.host.com'] } };",
        "responseOverride": {
            "headers": {
                "x-proxy": ["mockserver"]
            }
        }
    }
}))
package main

import (
    "bytes"
    "net/http"
)

func main() {
    body := []byte(`{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForwardTemplate": {
        "templateType": "JAVASCRIPT",
        "template": "return { 'path': '/target' + request.path, 'headers': { 'Host': ['target.host.com'] } };",
        "responseOverride": {
            "headers": {
                "x-proxy": ["mockserver"]
            }
        }
    }
}`)
    req, _ := http.NewRequest("PUT",
        "http://localhost:1080/mockserver/expectation",
        bytes.NewReader(body))
    req.Header.Set("Content-Type", "application/json")
    http.DefaultClient.Do(req)
}
using System.Net.Http;
using System.Text;

using var httpClient = new HttpClient();
var json = @"{
    ""httpRequest"": {
        ""path"": ""/some/path""
    },
    ""httpForwardTemplate"": {
        ""templateType"": ""JAVASCRIPT"",
        ""template"": ""return { 'path': '/target' + request.path, 'headers': { 'Host': ['target.host.com'] } };"",
        ""responseOverride"": {
            ""headers"": {
                ""x-proxy"": [""mockserver""]
            }
        }
    }
}";
await httpClient.PutAsync(
    "http://localhost:1080/mockserver/expectation",
    new StringContent(json, Encoding.UTF8, "application/json")
);
use reqwest::blocking::Client;

let client = Client::new();
let body = r#"{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForwardTemplate": {
        "templateType": "JAVASCRIPT",
        "template": "return { 'path': '/target' + request.path, 'headers': { 'Host': ['target.host.com'] } };",
        "responseOverride": {
            "headers": {
                "x-proxy": ["mockserver"]
            }
        }
    }
}"#;
client.put("http://localhost:1080/mockserver/expectation")
    .header("Content-Type", "application/json")
    .body(body.to_string())
    .send()
    .unwrap();
$json = <<<'JSON'
{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForwardTemplate": {
        "templateType": "JAVASCRIPT",
        "template": "return { 'path': '/target' + request.path, 'headers': { 'Host': ['target.host.com'] } };",
        "responseOverride": {
            "headers": {
                "x-proxy": ["mockserver"]
            }
        }
    }
}
JSON;

$ch = curl_init('http://localhost:1080/mockserver/expectation');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST  => 'PUT',
    CURLOPT_POSTFIELDS     => $json,
    CURLOPT_HTTPHEADER     => ['Content-Type: application/json; charset=utf-8'],
    CURLOPT_RETURNTRANSFER => true,
]);
curl_exec($ch);
curl_close($ch);
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpForwardTemplate": {
        "templateType": "JAVASCRIPT",
        "template": "return { 'path': '/target' + request.path, 'headers': { 'Host': ['target.host.com'] } };",
        "responseOverride": {
            "headers": {
                "x-proxy": ["mockserver"]
            }
        }
    }
}'

See REST API for full JSON specification

public class CallbackActionExamples {

    public void forwardClassCallback() {
        new ClientAndServer(1080)
            .when(
                request()
                    .withPath("/some.*")
            )
            .forward(
                callback()
                    .withCallbackClass(TestExpectationForwardCallback.class)
            );
    }

    public static class TestExpectationForwardCallback implements ExpectationForwardCallback {

        @Override
        public HttpRequest handle(HttpRequest httpRequest) {
            return request()
                .withPath(httpRequest.getPath())
                .withMethod("POST")
                .withHeaders(
                    header("x-callback", "test_callback_header"),
                    header("Content-Length", "a_callback_request".getBytes(UTF_8).length),
                    header("Connection", "keep-alive")
                )
                .withBody("a_callback_request");
        }
    }

}
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "path": "/some.*"
    },
    "httpForwardClassCallback": {
        "callbackClass": "org.mockserver.examples.mockserver.CallbackActionExamples$TestExpectationForwardCallback"
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);
from mockserver.client import MockServerClient
from mockserver.models import Expectation

client = MockServerClient("localhost", 1080)
client.upsert(Expectation.from_dict({
    "httpRequest" : {
        "path" : "/some.*"
    },
    "httpForwardClassCallback" : {
        "callbackClass" : "org.mockserver.examples.mockserver.CallbackActionExamples$TestExpectationForwardCallback"
    }
}))
require 'mockserver-client'

client = MockServer::Client.new('localhost', 1080)
client.upsert(MockServer::Expectation.from_hash({
    "httpRequest" : {
        "path" : "/some.*"
    },
    "httpForwardClassCallback" : {
        "callbackClass" : "org.mockserver.examples.mockserver.CallbackActionExamples$TestExpectationForwardCallback"
    }
}))
package main

import (
    "bytes"
    "net/http"
)

func main() {
    body := []byte(`{
    "httpRequest" : {
        "path" : "/some.*"
    },
    "httpForwardClassCallback" : {
        "callbackClass" : "org.mockserver.examples.mockserver.CallbackActionExamples$TestExpectationForwardCallback"
    }
}`)
    req, _ := http.NewRequest("PUT",
        "http://localhost:1080/mockserver/expectation",
        bytes.NewReader(body))
    req.Header.Set("Content-Type", "application/json")
    http.DefaultClient.Do(req)
}
using System.Net.Http;
using System.Text;

using var httpClient = new HttpClient();
var json = @"{
    ""httpRequest"" : {
        ""path"" : ""/some.*""
    },
    ""httpForwardClassCallback"" : {
        ""callbackClass"" : ""org.mockserver.examples.mockserver.CallbackActionExamples$TestExpectationForwardCallback""
    }
}";
await httpClient.PutAsync(
    "http://localhost:1080/mockserver/expectation",
    new StringContent(json, Encoding.UTF8, "application/json")
);
use reqwest::blocking::Client;

let client = Client::new();
let body = r#"{
    "httpRequest" : {
        "path" : "/some.*"
    },
    "httpForwardClassCallback" : {
        "callbackClass" : "org.mockserver.examples.mockserver.CallbackActionExamples$TestExpectationForwardCallback"
    }
}"#;
client.put("http://localhost:1080/mockserver/expectation")
    .header("Content-Type", "application/json")
    .body(body.to_string())
    .send()
    .unwrap();
$json = <<<'JSON'
{
    "httpRequest" : {
        "path" : "/some.*"
    },
    "httpForwardClassCallback" : {
        "callbackClass" : "org.mockserver.examples.mockserver.CallbackActionExamples$TestExpectationForwardCallback"
    }
}
JSON;

$ch = curl_init('http://localhost:1080/mockserver/expectation');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST  => 'PUT',
    CURLOPT_POSTFIELDS     => $json,
    CURLOPT_HTTPHEADER     => ['Content-Type: application/json; charset=utf-8'],
    CURLOPT_RETURNTRANSFER => true,
]);
curl_exec($ch);
curl_close($ch);
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest" : {
        "path" : "/some.*"
    },
    "httpForwardClassCallback" : {
        "callbackClass" : "org.mockserver.examples.mockserver.CallbackActionExamples$TestExpectationForwardCallback"
    }
}'

To use a class callback MockServer must be able to load the class from the classpath.

The callback class must:

If MockServer is started using the JUnit 4 @Rule, the JUnit 5 Test Extension, ClientAndServer or directly using org.mockserver.netty.MockServer then any class present in the main or test classpaths will be visible to MockServer.

If MockServer is started using the maven plugin only the non-forked goals (such as runAndWait and start) will be able to load classes from the main and test classpaths. It is possible to use classes from a separate maven dependency, however, this dependency must be specified in the plugin configuration dependencies section. Any dependency added to the plugin configuration dependencies section will then be visible to MockServer run using both forked and non-forked goals.

The following configuration shows how to use classes from a separate maven dependency in callback actions.

 <plugin>
     <groupId>org.mock-server</groupId>
     <artifactId>mockserver-maven-plugin</artifactId>
     <version>{{ site.mockserver_version }}</version>
     <configuration>
        <serverPort>1080</serverPort>
        <logLevel>DEBUG</logLevel>
        <pipeLogToConsole>true</pipeLogToConsole>
     </configuration>
     <executions>
         <execution>
             <id>pre-integration-test</id>
             <phase>pre-integration-test</phase>
             <goals>
                 <goal>runForked</goal>
             </goals>
         </execution>
         <execution>
             <id>post-integration-test</id>
             <phase>post-integration-test</phase>
             <goals>
                 <goal>stopForked</goal>
             </goals>
         </execution>
     </executions>
     <dependencies>
         <dependency>
             <groupId>com.my-domain</groupId>
             <artifactId>my-callback-dependency</artifactId>
             <version>1.0.0</version>
         </dependency>
     </dependencies>
 </plugin>

If MockServer is started using the command line then the callback classes must be added to the JVM using the classpath command line switch (cp or classpath). The classpath switch is ignored by the JVM if the jar switch is used. So to run the MockServer from the command line directly (with mockserver-netty-{{ site.mockserver_version }}-no-dependencies.jar) you must specify the org.mockserver.cli.Main main class specifically and not use the jar switch as follows.

java -Dfile.encoding=UTF-8 -cp mockserver-netty-{{ site.mockserver_version }}-no-dependencies.jar:my-callback-dependency.jar org.mockserver.cli.Main -serverPort 1080
new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .forward(
        new ExpectationForwardCallback() {
            @Override
            public HttpRequest handle(HttpRequest httpRequest) {
                return request()
                    .withPath(httpRequest.getPath())
                    .withMethod("POST")
                    .withHeaders(
                        header("x-callback", "test_callback_header"),
                        header("Content-Length", "a_callback_request".getBytes(UTF_8).length),
                        header("Connection", "keep-alive")
                    )
                    .withBody("a_callback_request");
            }
        }
    );
new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .forward(
        httpRequest -> request()
                    .withPath(httpRequest.getPath())
                    .withMethod("POST")
                    .withHeaders(
                        header("x-callback", "test_callback_header"),
                        header("Content-Length", "a_callback_request".getBytes(UTF_8).length),
                        header("Connection", "keep-alive")
                    )
                    .withBody("a_callback_request")
    );

When using org.mockserver.client.MockServerClient each method / closure callback has a separate web socket client. To ensure the number of total threads does not grow too large for large numbers of method / closure callback expectations the default event loop thread pool for the web socket client is kept fairly low. However, if an extremely large load is matched against a single method / closure callback expectation the event loop thread pool may not be large enough for its web socket client.

The number of threads for the event loop thread pool for each web socket client (i.e. for each expectation with a method / closure callback) can be configured and is described in the configuration section.

new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .forward(
        new ExpectationForwardCallback() {
            @Override
            public HttpRequest handle(HttpRequest httpRequest) throws Exception {
                return request()
                    .withPath(httpRequest.getPath())
                    .withMethod("POST")
                    .withHeaders(
                        header("x-callback", "test_callback_header"),
                        header("Content-Length", "a_callback_request".getBytes(UTF_8).length),
                        header("Connection", "keep-alive")
                    )
                    .withBody("a_callback_request");
            }
        },
        new ExpectationForwardAndResponseCallback() {
            @Override
            public HttpResponse handle(HttpRequest httpRequest, HttpResponse httpResponse) throws Exception {
                return httpResponse
                    .withHeader("x-response-test", "x-response-test")
                    .removeHeader(CONTENT_LENGTH.toString())
                    .withBody("some_overridden_response_body");
            }
        }
    );
new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path")
    )
    .forward(
        httpRequest ->
            request()
                .withPath(httpRequest.getPath())
                .withMethod("POST")
                .withHeaders(
                    header("x-callback", "test_callback_header"),
                    header("Content-Length", "a_callback_request".getBytes(UTF_8).length),
                    header("Connection", "keep-alive")
                )
                .withBody("a_callback_request"),
        (httpRequest, httpResponse) ->
            httpResponse
                .withHeader("x-response-test", "x-response-test")
                .removeHeader(CONTENT_LENGTH.toString())
                .withBody("some_overridden_response_body")
    );

When using org.mockserver.client.MockServerClient each method / closure callback has a separate web socket client. To ensure the number of total threads does not grow too large for large numbers of method / closure callback expectations the default event loop thread pool for the web socket client is kept fairly low. However, if an extremely large load is matched against a single method / closure callback expectation the event loop thread pool may not be large enough for its web socket client.

The number of threads for the event loop thread pool for each web socket client (i.e. for each expectation with a method / closure callback) can be configured and is described in the configuration section.