Reference requests and examples in mocks

View as Markdown

The pm.mock object provides structured, Postman-aware functions for matching incoming requests and sending responses with a mock. The pm.mock API can serve responses from your existing saved Postman examples rather than hard-coding everything.

pm.mock

Use the pm.mock methods to match incoming requests and send responses, including responses from your existing saved Postman examples.

In the following examples, <request-path> and <example-path> are placeholders for the path to a saved request and example in your local Git repo. The example’s status code, headers, and body are all sent as the response.

Rather than looking up paths manually, Postman provides a searchable dropdown directly in the mock code editor. When you click the argument, a dropdown list displays where you can search your workspace’s requests and examples by name or path.

pm.mock.matchRequest()

Matches an incoming request against a Postman request by its method, path, query parameters, and body. Returns true if the incoming request matches the specified criteria.

Example:

1if (pm.mock.matchRequest('<request-path>', req)) {
2 res.status(200).json([{ id: 1, name: 'Alice' }]);
3 return;
4}

pm.mock.sendExample()

Sends a saved Postman example as the HTTP response. This is the key integration point between your existing Postman collection data and your mock.

1if (pm.mock.matchRequest('<request-path>', req)) {
2 pm.mock.sendExample('<example-path>', res);
3 return;
4}

Below is a complete example using the pm.mock API:

1// Match GET /users and serve the saved "List Users - 200 OK" example
2if (pm.mock.matchRequest('<get-users-request-path>', req)) {
3 pm.mock.sendExample('<list-users-200-example-path>', res);
4 return;
5}
6
7// Match GET /users/:id with a path variable
8if (pm.mock.matchRequest('<request-path>', req)) {
9 if (req.params.id === '999') {
10 res.status(404).json({ error: 'User not found' });
11 } else {
12 pm.mock.sendExample('<get-user-200-example-path>', res);
13 }
14 return;
15}
16
17// Match POST /users
18if (pm.mock.matchRequest('<request-path>', req)) {
19 pm.mock.sendExample('<create-user-201-example-path>', res);
20 return;
21}
22
23res.status(404).json({ error: 'Route not matched' });

Path variable matching

The matching algorithm supports path variables, which are URL segments prefixed with : that match any value in that position.

Example:

1// Matches /products/42, /products/abc, /products/anything
2if (pm.mock.matchRequest('<request-path>', req)) {
3 console.log('Requested product ID:', req.params.id);
4 res.status(200).json({ id: req.params.id, name: 'Example Product' });
5 return;
6}
7
8// Nested path variables also work
9if (pm.mock.matchRequest('<request-path>', req)) {
10 res.status(200).json({
11 orgId: req.params.orgId,
12 userId: req.params.userId
13 });
14 return;
15}

Query parameter matching

Query parameter matching applies only when your saved request declares query parameters. A saved request declares them in two ways: as enabled parameter rows on the request, or as a query string on the saved request URL. Parameter rows that aren’t enabled are excluded. If the saved request declares no query parameters, this check is skipped and any query string on the incoming request is accepted.

When your saved request does declare query parameters, the incoming request must satisfy all of them to match:

  • Every declared parameter key must be present in the incoming request. A missing key fails the match.
  • Values must match. The comparison is string-based, so 1 and "1" are treated as the same value.
  • Keys are case-sensitive. role and Role are different parameters.
  • URL-encoded values are decoded before comparison, so hello%20world matches hello world.
  • A value that’s entirely a variable, such as {{workspaceId}}, matches any value except empty. ?ws= fails.
  • A variable embedded in text, such as v{{n}}, matches as a pattern and requires at least one character where the variable sits. v2 matches, v doesn’t.
  • If the saved request declares the same key more than once, the last value for that key is the one that must match.
  • Extra query parameters on the incoming request are ignored. They don’t prevent a match.

For a saved request of ?role=admin&ws={{workspaceId}}:

Incoming requestResult
?role=admin&ws=abcMatch
?role=admin&ws=abc&page=2Match, extra parameter ignored
?role=adminNo match, ws is missing
?role=user&ws=abcNo match, wrong role value
?role=admin&ws=No match, variable can’t be empty

Request body matching

Request body matching applies only when your saved request has a body. If it doesn’t, this check is skipped and the incoming body is ignored. When your saved request does have a body, the incoming request body must match it:

  • Matching applies to JSON bodies only. Postman parses the incoming body as JSON, so a body that isn’t valid JSON can’t match. Form-encoded and plain-text bodies never match a saved body.
  • The structure must match exactly at every nesting level: the same keys and the same number of keys. Both extra and missing fields fail the match, including inside nested objects. This is different from query parameters, where extra values are ignored.
  • Values are type-sensitive. 1 doesn’t match "1". This is different from query parameters, where the comparison is string-based.
  • Arrays must have the same length and the same order. [1,2] doesn’t match [2,1].
  • A saved string value that’s a variable, such as {{userId}}, matches any value, including an empty string and null.
  • If the incoming request sends no body and every value in the saved body is a variable, it matches. A saved body of {} requires the incoming body to be {} exactly.

For example, a saved body of { "status": "active", "id": "{{userId}}" } matches an incoming body of { "status": "active", "id": "42" }. It doesn’t match { "status": "active", "id": "42", "page": 2 }, because the incoming body has an extra field.

The matching algorithm matches on HTTP method, URL path, query parameters, and request body. It does not match on request headers.