> ## Documentation Index
> Fetch the complete documentation index at: https://moeck.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Request Matchers

> Match incoming requests by method, path, headers, body, and more.

A **request matcher** is the part of an [expectation](/mocking/expectations) that decides whether an incoming request should trigger the expectation's action. MockServer supports two matcher types:

* **Request properties matcher** — matches by HTTP properties such as method, path, headers, query parameters, cookies, and body
* **OpenAPI matcher** — matches against an OpenAPI v3 specification (see [OpenAPI](/mocking/openapi))

All string fields in a request properties matcher accept plain strings, Java-style regular expressions, or JSON Schema. Prefix a value with `!` (in JSON/REST) or wrap it with `not()` (in Java) to negate it. Prefix a key with `?` to make it optional.

## Method

<Tabs>
  <Tab title="Java">
    ```java theme={null}
    new MockServerClient("localhost", 1080)
        .when(
            request()
                .withMethod("GET")
                .withPath("/some/path")
                .withHeaders(
                    header("Accept", "application/json"),
                    header("Accept-Encoding", "gzip, deflate, br")
                )
        )
        .respond(
            response()
                .withBody("some_response_body")
        );
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    var mockServerClient = require('mockserver-client').mockServerClient;
    mockServerClient("localhost", 1080).mockAnyResponse({
        "httpRequest": {
            "method": "GET",
            "path": "/some/path",
            "headers": {
                "Accept": ["application/json"],
                "Accept-Encoding": ["gzip, deflate, br"]
            }
        },
        "httpResponse": {
            "body": "some_response_body"
        }
    });
    ```
  </Tab>

  <Tab title="REST API">
    ```bash theme={null}
    curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
      "httpRequest": {
        "method": "GET",
        "path": "/some/path",
        "headers": {
          "Accept": ["application/json"],
          "Accept-Encoding": ["gzip, deflate, br"]
        }
      },
      "httpResponse": {
        "body": "some_response_body"
      }
    }'
    ```
  </Tab>
</Tabs>

Use a regex to match multiple methods. To match any method except `GET`:

<Tabs>
  <Tab title="Java">
    ```java theme={null}
    request().withMethod(not("GET"))
    ```
  </Tab>

  <Tab title="REST API">
    ```json theme={null}
    { "method": "!GET" }
    ```
  </Tab>
</Tabs>

## Path

Match an exact path, a regex, or negate it.

<Tabs>
  <Tab title="Java">
    ```java theme={null}
    // exact
    request().withPath("/some/path")

    // regex — matches any path starting with /some
    request().withPath("/some.*")

    // negated — matches any path that does NOT start with /some
    request().withPath(not("/some.*"))
    ```
  </Tab>

  <Tab title="REST API">
    ```json theme={null}
    { "path": "/some/path" }
    { "path": "/some.*" }
    { "path": "!/some.*" }
    ```
  </Tab>
</Tabs>

## Path parameters

Use `{paramName}` placeholders in the path and specify values under `pathParameters`.

<Tabs>
  <Tab title="Java">
    ```java theme={null}
    new MockServerClient("localhost", 1080)
        .when(
            request()
                .withPath("/some/path/{cartId}")
                .withPathParameters(
                    param("cartId", "[A-Z0-9\\-]+")
                )
        )
        .respond(response().withBody("some_response_body"));
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    mockServerClient("localhost", 1080).mockAnyResponse({
        "httpRequest": {
            "path": "/some/path/{cartId}",
            "pathParameters": {
                "cartId": ["[A-Z0-9\\-]+"]
            }
        },
        "httpResponse": {
            "body": "some_response_body"
        }
    });
    ```
  </Tab>

  <Tab title="REST API">
    ```bash theme={null}
    curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
        "httpRequest": {
            "path": "/some/path/{cartId}",
            "pathParameters": {
                "cartId": ["[A-Z0-9\\-]+"]
            }
        },
        "httpResponse": {
            "body": "some_response_body"
        }
    }'
    ```
  </Tab>
</Tabs>

Use a JSON Schema value for more complex constraints:

```json theme={null}
"pathParameters": {
    "cartId": [{ "schema": { "type": "string", "pattern": "^[A-Z0-9-]+$" } }],
    "maxItemCount": [{ "schema": { "type": "integer" } }]
}
```

## Query parameters

<Tabs>
  <Tab title="Java">
    ```java theme={null}
    new MockServerClient("localhost", 1080)
        .when(
            request()
                .withMethod("GET")
                .withPath("/view/cart")
                .withQueryStringParameters(
                    param("cartId", "055CA455-1DF7-45BB-8535-4F83E7266092")
                )
        )
        .respond(response().withBody("some_response_body"));
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    mockServerClient("localhost", 1080).mockAnyResponse({
        "httpRequest": {
            "method": "GET",
            "path": "/view/cart",
            "queryStringParameters": {
                "cartId": ["055CA455-1DF7-45BB-8535-4F83E7266092"]
            }
        },
        "httpResponse": { "body": "some_response_body" }
    });
    ```
  </Tab>

  <Tab title="REST API">
    ```bash theme={null}
    curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
      "httpRequest": {
        "method": "GET",
        "path": "/view/cart",
        "queryStringParameters": {
          "cartId": ["055CA455-1DF7-45BB-8535-4F83E7266092"]
        }
      },
      "httpResponse": { "body": "some_response_body" }
    }'
    ```
  </Tab>
</Tabs>

Mark a parameter as **optional** by prefixing the key with `?`:

```json theme={null}
"queryStringParameters": {
    "?cartId": ["[A-Z0-9\\-]+"],
    "?maxItemCount": [{ "schema": { "type": "integer" } }]
}
```

By default, query parameter matching uses **SUB\_SET** mode — the request must contain at least one matching value per non-optional key, but may contain additional parameters. Set `"keyMatchStyle": "MATCHING_KEY"` to require all values for a key to match.

## Headers

<Tabs>
  <Tab title="Java">
    ```java theme={null}
    request()
        .withHeaders(
            header("Accept", "application/json"),
            header("Accept-Encoding", "gzip, deflate, br")
        )
    ```
  </Tab>

  <Tab title="REST API">
    ```json theme={null}
    "headers": {
        "Accept": ["application/json"],
        "Accept-Encoding": ["gzip, deflate, br"]
    }
    ```
  </Tab>
</Tabs>

Match headers with regex names or values:

```json theme={null}
"headers": {
    "Accept.*": [".*gzip.*"]
}
```

Negate a header value:

```json theme={null}
"headers": {
    "Accept": ["!application/json"],
    "Accept-Encoding": ["!.*gzip.*"]
}
```

Require a header to be absent:

```json theme={null}
"headers": {
    "!Accept": [".*"]
}
```

Use a JSON Schema to validate a header value:

```json theme={null}
"headers": {
    "Accept.*": [{ "schema": { "type": "string", "pattern": "^.*gzip.*$" } }]
}
```

Make a header optional:

```json theme={null}
"headers": {
    "?X-Optional-Header": ["some-value"]
}
```

## Cookies

Cookies follow the same pattern as headers but map each name to a single value.

<Tabs>
  <Tab title="Java">
    ```java theme={null}
    request()
        .withCookies(
            cookie("session", "4930456C-C718-476F-971F-CB8E047AB349")
        )
    ```
  </Tab>

  <Tab title="REST API">
    ```json theme={null}
    "cookies": {
        "session": "4930456C-C718-476F-971F-CB8E047AB349"
    }
    ```
  </Tab>
</Tabs>

Use a JSON Schema for the cookie value:

```json theme={null}
"cookies": {
    "session": { "schema": { "type": "string", "format": "uuid" } }
}
```

Mark a cookie as optional with the `?` prefix:

```json theme={null}
"cookies": {
    "?session": { "schema": { "type": "string", "format": "uuid" } }
}
```

## Body

MockServer supports many body match types.

<AccordionGroup>
  <Accordion title="Plain text (exact or substring)">
    Match exact body content:

    ```bash theme={null}
    curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
      "httpRequest": { "body": "some_exact_string" },
      "httpResponse": { "body": "some_response_body" }
    }'
    ```

    Match a substring using `subString: true`:

    ```json theme={null}
    "body": {
        "type": "STRING",
        "string": "some_string",
        "subString": true
    }
    ```
  </Accordion>

  <Accordion title="Regular expression">
    ```bash theme={null}
    curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
      "httpRequest": {
        "body": { "type": "REGEX", "regex": "starts_with_.*" }
      },
      "httpResponse": { "body": "some_response_body" }
    }'
    ```

    In Java: `.withBody(regex("starts_with_.*"))`
  </Accordion>

  <Accordion title="JSON (strict or partial)">
    Strict matching (all fields, array order, no extra fields):

    ```json theme={null}
    "body": {
        "type": "JSON",
        "json": { "id": 1, "name": "Scruffles" },
        "matchType": "STRICT"
    }
    ```

    Partial matching — only the fields you specify must be present:

    ```json theme={null}
    "body": {
        "type": "JSON",
        "json": { "name": "Scruffles" },
        "matchType": "ONLY_MATCHING_FIELDS"
    }
    ```

    Use JSONUnit placeholders to ignore fields or match by type:

    ```json theme={null}
    "body": {
        "type": "JSON",
        "json": { "id": "${json-unit.any-number}", "name": "${json-unit.ignore-element}" }
    }
    ```
  </Accordion>

  <Accordion title="JSON Schema">
    ```bash theme={null}
    curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
      "httpRequest": {
        "body": {
          "type": "JSON_SCHEMA",
          "jsonSchema": {
            "type": "object",
            "properties": {
              "id": { "type": "integer" },
              "name": { "type": "string" }
            },
            "required": ["id", "name"]
          }
        }
      },
      "httpResponse": { "body": "some_response_body" }
    }'
    ```
  </Accordion>

  <Accordion title="JsonPath">
    Matches if at least one value is returned by the expression:

    ```json theme={null}
    "body": {
        "type": "JSON_PATH",
        "jsonPath": "$.store.book[?(@.price < 10)]"
    }
    ```
  </Accordion>

  <Accordion title="XPath">
    Matches if at least one node is returned by the expression:

    ```bash theme={null}
    curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
      "httpRequest": {
        "body": {
          "type": "XPATH",
          "xpath": "/bookstore/book[price>30]/price"
        }
      },
      "httpResponse": { "body": "some_response_body" }
    }'
    ```

    In Java: `.withBody(xpath("/bookstore/book[price>30]/price"))`

    Negate the XPath match:

    ```json theme={null}
    "body": { "not": true, "type": "XPATH", "xpath": "/bookstore/book[price>30]/price" }
    ```
  </Accordion>

  <Accordion title="XML (exact or with placeholders)">
    Exact XML match:

    ```json theme={null}
    "body": {
        "type": "XML",
        "xml": "<bookstore><book nationality=\"ITALIAN\"><title>Everyday Italian</title></book></bookstore>"
    }
    ```

    Use XMLUnit placeholders to ignore elements or match by type:

    ```json theme={null}
    "body": {
        "type": "XML",
        "xml": "<bookstore><book><author>${xmlunit.ignore}</author><year>${xmlunit.isNumber}</year></book></bookstore>"
    }
    ```
  </Accordion>

  <Accordion title="XML Schema">
    ```json theme={null}
    "body": {
        "type": "XML_SCHEMA",
        "xmlSchema": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><xs:schema ...>...</xs:schema>"
    }
    ```
  </Accordion>

  <Accordion title="Form fields (URL-encoded)">
    ```bash theme={null}
    curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
      "httpRequest": {
        "method": "POST",
        "headers": { "Content-Type": ["application/x-www-form-urlencoded"] },
        "body": {
          "type": "PARAMETERS",
          "parameters": {
            "email": ["joe.blogs@gmail.com"],
            "password": ["secure_Password123"]
          }
        }
      },
      "httpResponse": { "body": "some_response_body" }
    }'
    ```
  </Accordion>
</AccordionGroup>

## Negation

Prefix any string value with `!` in JSON/REST to negate it. In Java, wrap it with `not()`:

```java theme={null}
request().withMethod(not("GET"))
request().withPath(not("/some.*"))
```

```json theme={null}
{ "method": "!GET" }
{ "path": "!/some.*" }
```

## OpenAPI matcher

You can also use an OpenAPI v3 specification as the request matcher. See [OpenAPI](/mocking/openapi) for details.

```json theme={null}
"httpRequest": {
    "specUrlOrPayload": "https://example.com/openapi.json",
    "operationId": "showPetById"
}
```
