Skip to content

Write dynamic responses with templates

Before you begin

Role
Editor or higher to write a template and Admin or higher to turn response templating on or off.

A mock’s response body and response header values can hold Handlebars expressions, which MockHub evaluates every time the mock answers. Use them to echo an ID from the path, return today’s date or answer differently depending on what the caller sent.

Templating is on for every new project. It is the Response templating switch under Responses and logging in the project’s Settings; with it off, expressions are sent exactly as written. See Set a project’s logging and templating.

Each mock also has its own Response templating under What it answers. Follow the project, the default, renders expressions while the project’s switch is on. Serve as written sends the mock’s body and headers exactly as written whatever the project says, so a response that must contain {{, such as a template for another system, stays as it is. A mock served as written that saves to the data store saves its body as written too.

  1. On the project’s Mocks tab, select the mock’s name.

  2. In Response body, type {{ where a value belongs. The editor suggests helpers and the parts of the request you can read; Suggest in the editor toolbar opens the same list.

  3. Complete the expressions. This body belongs to a mock whose Path with parameters is /orders/{id}:

    {
    "id": "{{request.path.id}}",
    "currency": "{{val request.query.currency or='EUR'}}",
    "createdAt": "{{now format='yyyy-MM-dd'}}",
    "deliveryDate": "{{now offset='+3 days' format='yyyy-MM-dd'}}"
    }
  4. Select Save mock.

  5. Call the mock:

    Terminal window
    curl 'https://orders-api.mockhub.dev/orders/42?currency=USD'

To see the rendered body before saving, use Try it; see Test a mock before saving.

The response carries the values of this request:

{
"id": "42",
"currency": "USD",
"createdAt": "2026-09-30",
"deliveryDate": "2026-10-03"
}

Without ?currency=, currency falls back to EUR.

Expression Gives
request.path The path, such as /orders/42
request.url The path and the query string
request.path.<name> The part of the path a {name} of a Path with parameters matched, as sent: Jane%20Doe stays encoded
request.pathSegments.[n] One part of the path, counted from 0: in /orders/42, [0] is orders and [1] 42
request.query.<name> A query parameter
request.headers.<Name> A request header, such as request.headers.X-Request-Id
request.cookies.<name> A cookie
request.method The method, such as GET
request.body The body as text. Read one JSON field with jsonPath request.body '$.customer.name'
request.id A unique ID for this request

The helpers, such as now, val, jsonPath, randomValue, math and each, are listed with examples in Template helpers. Realistic names, addresses and numbers come from random: see Fill responses with fake data.

Keep the body valid when a value comes from the caller

Section titled “Keep the body valid when a value comes from the caller”

A value from the request can be missing, and the caller can put a quote in it. Either one can break a body written as "name": "{{jsonPath request.body '$.name'}}". Write the value with toJson and a default instead, with no quotes around the expression: toJson adds the quotes, escapes the text and keeps a number as a number.

{
"name": {{toJson (jsonPath request.body '$.name' default='Unnamed')}},
"age": {{toJson (jsonPath request.body '$.age' default=0)}},
"q": {{toJson (val request.query.q default='')}}
}

A POST to /users?q=shoes with the body {"name": "Ann \"Bo\" Lee", "age": 42} gets valid JSON:

{
"name": "Ann \"Bo\" Lee",
"age": 42,
"q": "shoes"
}

Without those values, the same mock answers with "Unnamed", 0 and "".

In XML, a & or < in a value breaks the document, so put the expression in CDATA:

<publisher><![CDATA[{{request.query.publisher}}]]></publisher>

Answer differently depending on the request

Section titled “Answer differently depending on the request”

A block helper chooses between two parts of the body:

{{#if (eq request.query.status.first 'shipped')}}
{"orders": [{"id": 42, "status": "shipped"}]}
{{else}}
{"orders": []}
{{/if}}

A query parameter, header or cookie can arrive more than once, so each is a list of values. Written on its own it prints the first value, but in a comparison add .first: (eq request.query.status 'shipped') is never true. Compare the method as request.method.name. The editor warns about both.

That first value is text. For equality compare it with a quoted number, (eq request.query.page.first '2'); with a bare 2 it is never equal. To order it, make it a number first: (gte (math request.query.page.first '+' 0) 2). Without math, gte, gt, lte and lt fail the whole response.

Keep a space or a line break between an expression and a closing } of your JSON: {{now}}} reads as the end of a triple-brace expression and fails.

The editor underlines what it knows is wrong as you type, such as an unclosed {{#if}} or a part of request that does not exist. The rest shows when the mock answers:

  • A syntax mistake, a helper that fails, or a fake value that cannot be generated fails the whole response. The caller gets a 500 Mock response did not render error in its place, and the project’s request log says why in plain words. Try it shows the mock server’s report, which names the problem, quotes the line and points at it. Only the first problem is reported:

    [ERROR] 1:2: could not find helper: 'nowx'
    {{nowx 'b'}}
    ^

    The position counts from the first {{ in the body, not from the start of the body: line 1 is the line that holds it, and on that line column 0 is that {{. Columns count from 0. In a JSON body whose first expression is on the second line, a report on that expression therefore says line 1.

  • An operator math does not know, and a jsonPath or xPath on a request body that is not JSON or XML, write the error in place of the value, and the rest of the body renders with the mock’s own status:

    [ERROR: ^ is not a valid mathematical operator]
  • Some mistakes print nothing at all: a jsonPath that finds no field, a part of request that does not exist, and a name without arguments that is no helper, such as {{nowx}}.

Try it lists both kinds of report before you save; see Test a mock before saving and A mock’s response did not render.

  • An expression reads the request being answered and the project’s data store. A value from an earlier request is there only if a mock saved it.
  • request.host, request.port, request.scheme and request.baseUrl are the address your caller used, such as orders-api.mockhub.dev, 443, https and https://orders-api.mockhub.dev, also on a custom domain. A header the caller sends cannot change them.
  • The editor checks the helpers it knows, and does not flag a helper name it has never heard of. Try it reports an unknown helper that has arguments; one without arguments prints nothing.
  • A jsonPath filter that compares with a regular expression, such as [?(@.sku =~ /B-.*/)], runs it within the same step limit as a matching rule’s regular expression. A comparison that needs more steps is cut short and selects nothing, without an error.
  • Templates apply to the response only. What a mock matches is set by its matching rules; see Match requests.

Report a problem with this page