Use Request Data To Create Dynamic Mock Response
Beeceptor uses the Handlebars templating engine to craft dynamic mock responses. This allows you to pull in data from request payloads and query parameters, enabling tailored responses for each request.
Enabling Templating
Beeceptor converts incoming request payloads and query parameters into a JSON object. This object is available to the templating engine, which then substitutes these values into your mock responses. Before using this feature, here are some key points to consider:
Key Facts about the Template Engine:
- The template engine uses Handlebars syntax #. Expressions are enclosed in
{{
and}}
, and when processed, they are replaced with corresponding values from the request. - By default, the template engine is off. You must explicitly enable it for each specific rule.
- HTML Encoding: Use the triple-stache (
{{{
and}}}
) syntax when you need to output values without escaping the content. The standard{{
and}}
will encode HTML special characters, which may be useful for preventing HTML injection but can alter your response format if not intended. Here's a list of the main characters that Handlebars escapes by default (when using double-stache):&
becomes&
<
becomes<
>
becomes>
"
becomes"
'
becomes'
=
becomes=
- If there’s a syntax error in the template, Beeceptor will attempt to recover and generate a response. However, if recovery fails, a
561
status code is returned. In these cases, you should review and correct the template syntax. - Beeceptor offers following helpers that allow you to easily reuse request parameters for building a dynamic response.
Request Data Helpers
These helpers allow you to extract request parameters and use them in the mocked response.
Supported Content Types
Beeceptor supports the following content types for extracting request parameters. The request payload is parsed only if the incoming Content-Type
matches one of the following:
- JSON Payloads:
application/json
,application/ld+json
, etc. - Form URL Encoded:
application/x-www-form-urlencoded
- XML/SOAP Payloads:
text/xml
,application/xml
,application/soap+xml
, etc. For more details on XML to JSON conversion and SOAP examples, refer to this section.
Request Body
The body
helper extracts the request payload/body from JSON, XML, or Form URL Encoded requests. All content types are parsed into a JSON object to be used in the template. This typically applies to HTTP verbs like POST
, PATCH
, and PUT
.
Syntax:
{{body 'path' 'default-value'}}
Request Query Parameters
The queryParam
helper extracts query parameters and converts them into a JSON object for use in the template. This works for all HTTP verbs.
Syntax:
{{queryParam 'path' 'default-value'}}
The path
parameter above allows you to access deep properties in a JSON object, such as keyName
, parent.child
, or keyName.1.childKey
.
Request Path Component
If your rule uses regular expressions (RegEx) to match a request path, you can use named groups. These named groups and their values are available via the pathParam
helper.
Syntax:
{{pathParam 'group-name' 'default-value'}}
For example, if your rule defines named groups entity_id
and child_id
, you can access them in the template as shown below:
Request Headers
The header
helper extracts request headers for use in the template. Headers are case-insensitive, so you should use lowercase in the syntax.
Syntax:
{{header 'header-name' 'default-value'}}
Here's an example:
The default-value
parameter is optional. If no matching value is found, it falls back to an empty string.
Example Templates
JSON Request Payloads
Flat & nested fields
Consider the following example of a JSON request payload:
Request: Request payload entering with application/json
content-type at server path /my-rule?type=individual
{
"address": "80, Pearl Residency, MG Road, India",
"age": 20,
"name": {"first": "Arti", "last": "Jain"}
}
Mocking Template: Here is an example mocking template defined in a rule.
{
"type": "{{queryParam 'type'}}",
"address": "{{body 'address'}}",
"age": {{body 'age' '0'}},
"full_name": "{{body 'name.first'}} - {{body 'name.last'}}"
}
Note: If the age
attribute is missing from the request body, a default value of 0 is used.
Response: Beeceptor would generate the following response. The value individual
for type, comes from the query parameter, and the rest from the JSON payload.
{
"type": "individual",
"address": "80, Pearl Residency, MG Road, India",
"age": 20,
"full_name": "Arti - Jain"
}
Using arrays
If your request contains an array of items, such as in an order, you can reference array elements by their index.
Request: The following shows a request payload with an array of line items.
{
"line_items": [
{
"id": 110,
"name": "30g (>1oz) Tiger Tail Pack (Cordyceps Militaris)",
"product_id": 433,
"quantity": 1,
"subtotal": "60.00",
"total": "60.00",
"taxes": [],
"sku": "23423",
"price": 60,
}
]
}
Mocking Template: The following template accesses the line items in the array:
{
"products": [
{
"productId": "{{body 'line_items.0.id'}}",
"quantity": {{body 'line_items.0.quantity'}},
"price": {{body 'line_items.0.total'}}
}
]
}
Response: Beeceptor would generate this response:
{
"products": [
{
"productId": "110",
"quantity": 1,
"price": 60
}
]
}
Form URL-Encoded Payloads
Form URL encoding is a common way of data transfer in HTTP requests, especially in website forms. When the data is sent with the application/x-www-form-urlencoded
content type, key-value pairs are encoded into the body of the request. Beeceptor parses these and lets you use them in mock templates. Here are some examples.
Single-Value Key-Value Pairs
Request: In this case, the request payload contains a set of key-value pairs with a single value assigned to each key. Below is an example of a POST request containing URL-encoded form data:
POST /submit-order HTTP/1.1
Host: endpoint.proxy.beeceptor.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 48
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36
Accept: */*
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
type=domestic&orderid=23324&customerName=Bob
Mocking Template: In Beeceptor, you can create a response template to handle and extract the key-value pairs from the body of the request using the {{body}}
helper method.
Response: When the above request is sent, Beeceptor will generate the following response based on the provided template:
Type: domestic
OrderID: 23324
CustomerName: Bob
Multiple Values in URL-Encoding
In some cases, multiple values may be sent for the same key in the URL-encoded data. This can happen when, for example, a form allows multiple selections, and each value is sent under the same key. These are treated as array elements.
Request: The request contains URL-encoded data with content type application/x-www-form-urlencoded
.
POST /submit-order HTTP/1.1
Host: endpoint.proxy.beeceptor.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 48
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36
Accept: */*
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
key1=value1-first&key2=value2&key3=value3&key1=value1-repeat
In this request, the key key1
appears twice, meaning it has two values: value1-first
and value1-repeat
.
Mocking Template: To extract multiple values from, Beeceptor allows you to reference array elements using the {{body 'key.n'}}
syntax, where n
is the index of the item.
{
"value": "{{body 'key1'}}",
"value1-first": "{{body 'key1.0'}}",
"value1-second": "{{body 'key1.1'}}"
}
Response: Beeceptor processes the request and generates the following response:
{
"value": "value1-first,value1-repeat",
"value1-first": "value1-first",
"value1-second": "value1-repeat"
}
XML Request Payloads
When Beeceptor receives an XML payload, it automatically converts the XML data into a JSON object, making it easier to access elements and attributes in your mock templates. Let’s go through few examples of how XML is transformed into JSON and how to use this in a mock rule.
Attributes in XML
<person name="John" age="30" />
Intermittent JSON Object in Beeceptor:
{
"person": {
"@_name": "John",
"@_age": "30"
}
}
You can access XML attributes in a mock rule like this:
Nested Elements in XML
If the XML contains nested elements:
<person>
<name>John</name>
<address>
<city>New York</city>
<state>NY</state>
</address>
</person>
Intermittent JSON Object in Beeceptor:
{
"person": {
"name": "John",
"address": {
"city": "New York",
"state": "NY"
}
}
}
You can access nested elements like this:
XML With All Features
XML (eXtensible Markup Language) is widely used for structured data transfer. Beeceptor supports XML parameter extraction using the same dot notation.
1: Nested XML Example
Here’s an example of an XML request that represents a catalog of books. Each book contains attributes and elements such as title, author, year, and price.
<bookstore>
<book category="fiction">
<title lang="en">The Catcher in the Rye</title>
<author>J.D. Salinger</author>
<year>1951</year>
<price>19.99</price>
</book>
<book category="science">
<title lang="en">A Brief History of Time</title>
<author>Stephen Hawking</author>
<year>1988</year>
<price>15.99</price>
</book>
</bookstore>
2: Intermittent JSON Object in Beeceptor
When Beeceptor parses the XML, it converts it into the following JSON object. Notice how the elements and attributes are represented:
{
"bookstore": {
"book": [
{
"@_category": "fiction",
"title": {
"@_lang": "en",
"#text": "The Catcher in the Rye"
},
"author": "J.D. Salinger",
"year": "1951",
"price": "19.99"
},
{
"@_category": "science",
"title": {
"@_lang": "en",
"#text": "A Brief History of Time"
},
"author": "Stephen Hawking",
"year": "1988",
"price": "15.99"
}
]
}
}
In this JSON structure:
- The
@_
prefix is used to denote XML attributes (e.g.,category
andlang
). - Text content inside elements is represented by the
#text
key (e.g., the title of the book).
3: Usage in Mock Rule Template
You can now use this converted JSON object in your mock rules. Suppose you want to create a mock response that extracts and displays the first book’s title, author, and price.
{
"firstBook": {
"title": "{{body 'bookstore.book.0.title.#text'}}",
"titleLang": "{{body 'bookstore.book.0.title.@_lang'}}",
"author": "{{body 'bookstore.book.0.author'}}",
"price": "{{body 'bookstore.book.0.price'}}"
},
"category": "{{body 'bookstore.book.0.@_category'}}",
"secondBookTitle": "{{body 'bookstore.book.1.title.#text'}}"
}
4: Beeceptor's response
{
"firstBook": {
"title": "The Catcher in the Rye",
"titleLang": "en",
"author": "J.D. Salinger",
"price": "19.99"
},
"category": "fiction",
"secondBookTitle": "A Brief History of Time"
}
SOAP Request Envelope
SOAP requests typically follow a specific structure, which includes an Envelope
, Header
, and Body
. The Envelope
serves as the root element and wraps all the data, while the Body
contains the actual request payload. Beeceptor makes it easy to work with these SOAP requests by parsing the XML and converting it into a JSON object. This allows you to easily access elements like the envelope, header, and request parameters in your mock rules.
If you receive a SOAP request:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://www.example.com/webservice">
<soapenv:Header/>
<soapenv:Body>
<web:GetCityWeatherByZIP>
<web:ZIP>10001</web:ZIP>
</web:GetCityWeatherByZIP>
</soapenv:Body>
</soapenv:Envelope>
Beeceptor parses the SOAP envelope and converts it to a simplified JSON object, which you can then use in your templates.
Intermittent JSON object in Beeceptor
Beeceptor removes the XML namespace complexity and structures the SOAP request into a JSON format. This makes it straightforward to access the envelope, headers, and body parameters within your template.
{
"Envelope": {
"Header": {},
"Body": {
"GetCityWeatherByZIP": {
"ZIP": "10001"
}
}
}
}
In the above JSON structure:
- The
Envelope
is the root, encapsulating theHeader
andBody
. - The
Body
contains the actual request data, such asGetCityWeatherByZIP
and its parameterZIP
.
You can access these parameters in your templates by referencing the path using dot notation on JSON object. For example, you would use the body helper to fetch the ZIP code from the parsed SOAP request.
Accessing Request Parameters in the Mocking Template
Here’s an example template that uses the ZIP
code from the SOAP request to generate a mock response with dynamic data.
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://www.example.com/webservice">
<soapenv:Body>
<web:GetCityWeatherByZIPResponse>
<web:CityWeather>
<web:City>New York</web:City>
<web:ZIP>{{body 'Envelope.Body.GetCityWeatherByZIP.ZIP'}}</web:ZIP>
<web:Weather>Cloudy</web:Weather>
<web:Temperature>18</web:Temperature>
<web:Humidity>{{faker 'number.int' '100'}}</web:Humidity>
</web:CityWeather>
</web:GetCityWeatherByZIPResponse>
</soapenv:Body>
</soapenv:Envelope>
Key Points on Handling SOAP Requests
- Namespaces: Beeceptor automatically handles the XML namespaces in SOAP requests, stripping them out so you don’t have to worry about them when writing mock templates.
- Accessing Nested Elements: You can easily access deeply nested elements within the SOAP body using the
body
helper with dot notation. For example, to accessZIP
in the SOAP body, you can use{{body 'Envelope.Body.GetCityWeatherByZIP.ZIP'}}
. - Handling Missing Data: If a parameter is missing from the SOAP request, you can provide a default value in the template using the
body
helper's second parameter. For example:{{body 'Envelope.Body.GetCityWeatherByZIP.ZIP' 'Unknown'}}
. - Dummy Values: You can combine the
faker
helper to generate random data in the mocked response, allowing for more dynamic and realistic test scenarios.