Template Mocks - Version 1.0 (deprecated)¶
The version 1.0 of Template Mocks is deprecated and available only for accounts created before September 2020. We still support this version, though, but it is impossible to use it for accounts created after September 1st, 2020. If you have any questions, please contact our support at support@smartmock.io.
Request Model¶
The HTTP request is parsed and supplied to the template mock. The following request attributes are available:
Method¶
req.method
- Value of request HTTP method.
URL¶
req.url
- The URL, the client, used to make the request. The returned URL contains a protocol, server name, port number,
and the server path, but it does not include query string parameters.
Example
Request URL:
http://somedomain.app.smartmock.io/user/John%20Doe/permissions?param1=value1
Template:
{{req.url}}
Rendered response body:
http://somedomain.app.smartmock.io/user/John%20Doe/permissions
Path¶
req.path
- The path part of the request's URL. It does not decode the path.
Example
Request URL:
http://somedomain.app.smartmock.io/user/John%20Doe/permissions?param1=value1
Template:
{{req.path}}
Rendered response body:
/user/John%20Doe/permissions
Path Parameters¶
req.pathParams.[name]
- Value of path parameter (see Path Parameter Matchers) extracted from request path.
If the parameter not found, the empty string is used.
Example
Path matcher:
/user/{userId}/permissions
Request URL:
http://somedomain.app.smartmock.io/user/123abc/permissions?param1=value1
Template:
{{req.pathParams.[userId]}}
Rendered response body:
123abc
Path Segments¶
req.pathSegments.[n]
- Value of nth URL path segment. Zero indexed. If segment not found, the empty string is used.
Example
Request URL:
http://somedomain.app.smartmock.io/user/123abc/permissions?param1=value1
Template:
{{req.pathSegments.[1]}}
Rendered response body:
123abc
Host¶
req.host
- Name of the host the request is made to.
Example
Request URL:
http://somedomain.app.smartmock.io/user/123abc/permissions?param1=value1
Template:
{{req.host}}
Rendered response body:
somedomain.app.smartmock.io
Headers¶
req.headers.[name]
- Value of first request header with the given name. If value not found, the empty string is used.
req.headers.[name].[n]
- Value of nth request header with the given name. Zero indexed. If value not found, the empty string is used.
Example
Request Headers:
Content-Type: application/json
AuthToken: abc123
AuthToken: bcd123
Template:
{{req.headers.[AuthToken]}} - {{req.headers.[AuthToken].[1]}}
Rendered response body:
abc123 bcd123
Cookies¶
req.cookies.[name]
- Value of first request cookie with the given name. If value not found, the empty string is used.
req.cookies.[name].[n]
- Value of nth request cookie with the given name. Zero indexed. If value not found, the empty string is used.
Example
Request Headers:
Cookie: PHPSESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;
Template:
{{req.cookies.[PHPSESSID]}}
Rendered response body:
298zf09hf012fh2
Query Parameters¶
req.query.[name]
- Value of first request query parameter with the given name. If value not found, the empty string is used.
req.query.[name].[n]
- Value of nth request query parameter with the given name. Zero indexed. If value not found, the empty string is used.
Example
Request URL:
http://somedomain.app.smartmock.io/user/123abc/permissions?page=1&size=10
Template:
{{req.query.[page]}}
Rendered response body:
1
Query String¶
req.queryString
- Value of request URL query string. If the request URL has no query string, the empty string will is used.
Example
Request URL:
http://somedomain.app.smartmock.io/user/123abc/permissions?page=1&size=10
Template:
{{req.queryString}}
Rendered response body:
page=1&size=10
Body¶
req.body
- Value of request body.
Example
Request body:
{"id" : 123, "name": "John", "surname" : "Doe"}
Template:
{{req.body}}
Rendered response body:
{"id" : 123, "name": "John", "surname" : "Doe"}
Helpers¶
Besides accessing request fields, it's possible to include some logic in the form of helpers.
Random UUID Helper¶
randomUuid
- Generates UUID type 4 value.
Example
Template:
{{randomUuid}}
Rendered response body:
400bc69f-9b06-43c2-8497-ba8755fe7ef6
Date/Time Helper¶
now format='<format>' offset='<offset>' timezone='<zone>'
- Generates string value of current time in given zone, with given format, adding given offset.
Example 1
Template:
{{now format='yyyy-MM-dd\' at \'HH:mm:ss' offset='-1 hours' timezone='UTC'}}
Rendered response body:
2018-05-10 at 11:12:13
Example 2
Template:
{{now}}
Rendered response body:
2018-05-10T11:12:13Z
Parameters¶
Parameter | Description | Default value |
---|---|---|
format | Patterns based on a simple sequence of letters and symbols. Use "\" to escape single quote characters in format string. See detail below. | ISO-8601 extended offset date-time format (yyyy-MM-dd'T'HH:mm:ssX ) |
offset | Add or remove seconds/minutes/hours/days/months/years. Format: +/-<number> <unit> examples: +1 year , -2 months |
-0 seconds |
timezone | Time zone date(time) will be placed in. Sample values: UTC+02:00 , ECT , PST , EST |
UTC |
Format details¶
All letters 'A' to 'Z' and 'a' to 'z' are reserved as pattern letters. The following pattern letters are defined:
Symbol Meaning Presentation Examples
------ ------- ------------ -------
G era text AD; Anno Domini; A
u year year 2004; 04
y year-of-era year 2004; 04
D day-of-year number 189
M/L month-of-year number/text 7; 07; Jul; July; J
d day-of-month number 10
Q/q quarter-of-year number/text 3; 03; Q3; 3rd quarter
Y week-based-year year 1996; 96
w week-of-week-based-year number 27
W week-of-month number 4
E day-of-week text Tue; Tuesday; T
e/c localized day-of-week number/text 2; 02; Tue; Tuesday; T
F week-of-month number 3
a am-pm-of-day text PM
h clock-hour-of-am-pm (1-12) number 12
K hour-of-am-pm (0-11) number 0
k clock-hour-of-am-pm (1-24) number 0
H hour-of-day (0-23) number 0
m minute-of-hour number 30
s second-of-minute number 55
S fraction-of-second fraction 978
A milli-of-day number 1234
n nano-of-second number 987654321
N nano-of-day number 1234000000
V time-zone ID zone-id America/Los_Angeles; Z; -08:30
z time-zone name zone-name Pacific Standard Time; PST
O localized zone-offset offset-O GMT+8; GMT+08:00; UTC-08:00;
X zone-offset 'Z' for zero offset-X Z; -08; -0830; -08:30; -083015; -08:30:15;
x zone-offset offset-x +0000; -08; -0830; -08:30; -083015; -08:30:15;
Z zone-offset offset-Z +0000; -0800; -08:00;
p pad next pad modifier 1
' escape for text delimiter
'' single quote literal '
[ optional section start
] optional section end
# reserved for future use
{ reserved for future use
} reserved for future use
The count of pattern letters determines the format.
Unix Timestamp Helper¶
unixTimestamp unit='<unit>'
- Generates string representing number of milliseconds, seconds, minutes, hours, days since Jan 01 1970. (UTC)
Parameter | Description | Default value |
---|---|---|
unit | Time unit of timestamp. Possible values: MILLISECONDS , SECONDS , MINUTES , HOURS , DAYS |
SECONDS |
Random String Helper¶
randomString length=<length> type='<type>' case='<case>'
- Generates random string of given type with given length and given case.
Parameter | Description | Default value |
---|---|---|
length | Length of string | 10 |
type | Type of string. Possible types: ALPHABETIC , ALPHANUMERIC , NUMERIC , ALPHANUMERIC_AND_SYMBOLS |
ALPHABETIC |
case | Defines if letters are upper case or lower case. Possible values: UPPER , LOWER , none |
none |
Example 1 (alphabetic string)
Template:
{{randomString}}
Rendered response body:
EhFGqGiZpK
Example 2 (numeric string)
Template:
{{randomString length=5 type='NUMERIC'}}
Rendered response body:
22187
Example 3 (alphanumeric upper case string)
Template:
{{randomString length=20 type='ALPHANUMERIC' case='UPPER'}}
Rendered response body:
2TFO8F6YM0XBHFVGDZER
Random Number Helper¶
randomNumber min=<min> max=<max> fractionDigits=<digits>
- Generates random number greater or equal to min
and lower than max
with given number of fraction digits
Parameter | Description | Default value |
---|---|---|
min | inclusive minimum | 0 |
max | exclusive maximum | 100 |
fractionDigits | Number of fraction digits - useful for generating float values | 0 |
Example 1
Template:
{{randomNumber}}
Rendered response body:
82
Example 2
Template:
{{randomNumber min=1000 max=100000 fractionDigits=5}}
Rendered response body:
67342.60221
Random Data Helper¶
{{randomData type='<type>' locale='<locale>'}}
- Generates random data of given type (name, street, cc number, etc.) with given locale.
Parameter | Description | Default value |
---|---|---|
type | What kind of data to generate. Supported data types are: FIRST_NAME , MIDDLE_NAME , LAST_NAME , EMAIL , NIC , PASSPORT_NUMBER , PHONE_NUMBER , STREET , STREET_NUMBER , POSTAL_CODE , CITY , IBAN_NUMBER , CC_NUMBER , CVV , CC_EXPIRATION_DATE |
none |
locale | What locale to use while generating data. Supported locales are: en , es , pl , de , fr , it , ka , sv , zh |
en |
Example
Template:
{{randomData type='FIRST_NAME' locale='en'}} {{randomData type='LAST_NAME' locale='en'}}
Rendered response body:
John Watson
String Helpers¶
All listed String Helpers are provided by Java implementation of Handlebard by jknack.
{{capitalizeFirst <value>}}
- Capitalizes the first character of the value.
Example
Request body:
aaaaaaa
Template:
{{capitalizeFirst req.body}}
Rendered response body:
Aaaaaaa
{{center <value> size=<size> [pad='<char>'] }}
- Centers the value in a field of a given width using provided pad character (default ' ').
Example
Request body:
aaaaaaa
Template:
{{center req.body size=19 pad='b'}}
Rendered response body:
bbbbbbaaaaaaabbbbbb
{{cut <value> '<arg>'}}
- Removes all values of arg from a given string.
Example
Request body:
aaaabbbbaaa
Template:
{{cut req.body 'b'}}
Rendered response body:
aaaaaaa
{{defaultIfEmpty <value> ['nothing'] }}
- Uses given default when value resolved to false.
Example
Template:
{{defaultIfEmpty req.not_existing_field "nothing"}}
Rendered response body:
nothing
{{join <value> '<string>' [prefix='<prefix>'] [suffix='<suffix>']}}
- Joins an array with a string using optional prefix and suffix values.
Example
Request headers:
Header1: Value1
Header1: Value2
Template:
{{join req.headers.[Header1] 'aaa' prefix='s' suffix='d'}}
Rendered response body:
sValue1aaaValue2d
{{ljust <value> size=<size> pad=' ' }}
- Left-aligns the value in a field of a given width with given character (default ' ').
Example
Request headers:
Header1: Value1
Header1: Value2
Template:
{{ljust req.headers.[Header1].[1] size=20 pad='d'}}
Rendered response body:
Value2dddddddddddddd
{{rjust <value> size=<size> pad=' ' }}
- Right-aligns the value in a field of a given width with given character (default ' ').
Example
Request headers:
Header1: Value1
Header1: Value2
Template:
{{rjust req.headers.[Header1].[1] size=20 pad='d'}}
Rendered response body:
ddddddddddddddValue2
{{substring <value> <start> <end> }}
- Returns string that is a substring of given value. The substring starts with the character value at the specified start
index and
ends with the character value at index end - 1
Example
Request body:
aaaabbbbaaa
Template:
{{substring req.body 1 5}}
Rendered response body:
aaab
{{lower <value>}}
- Converts a string into all lowercase.
Example
Request body:
AAAA
Template:
{{lower req.body}}
Rendered response body:
aaaa
{{upper <value>}}
- Converts a string into all uppercase.
Example
Request body:
aaaa
Template:
{{upper req.body}}
Rendered response body:
AAAA
{{slugify <value>}}
- Converts a string to a slug. Converts to lowercase, removes non-word characters (alphanumerics and underscores) and converts spaces to dashes. Also, strips leading and trailing whitespace.
Example
Request body:
aaaa_!@#sss_ssss jkjhkjH
Template:
{{slugify req.body}}
Rendered response body:
aaaasssssss-jkjhkjh
{{stringFormat <value> param0 param1 ... paramN}}
- Formats the variable according to the argument, a string formatting specifier.
[See more](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#format(java.lang.String,%20java.lang.Object...)
Example
Request body:
aaaa%s
Template:
{{stringFormat req.body 'bbbb'}}
Rendered response body:
aaaabbbb
{{ capitalize <value> fully=true/false}}
- Capitalizes all the whitespace separated words in a string.
Example
Request body:
hello world
Template:
{{capitalize req.body fully=true}}
Rendered response body:
Hello World
{{abbreviate <value> <size> }}
- Truncates a string if it is longer than the specified number of characters (size).
Truncated strings end with a translatable ellipsis sequence ("...").
Example
Request body:
hello world
Template:
{{abbreviate req.body 6}}
Rendered response body:
hel...
{{ wordWrap <value> <length> }}
- Wraps words at specified line length
.
Example
Request body:
hello world
Template:
{{wordWrap req.body 4}}
Rendered response body:
hello
world
{{ replace <value> '<target>' '<replacement>' }}
- Replaces each substring of this string that matches the literal target
sequence with the specified literal replacement
sequence.
Example
Request body:
hello world
Template:
{{replace req.body 'world' 'you'}}
Rendered response body:
hello you
JSON Path Helper¶
{{jsonPath <value> path='<path>' pretty=<true/false>}}
- Evaluates JSONPath expression. JSONPath is a query language for JSON, similar to XPath for XML.
This helper allows extracting data from a JSON request body. See more about JSONPath.
Parameter | Description | Default value |
---|---|---|
path | Valid JSONPath expression Tester. If path is incorrect empty string will be returned. | none |
pretty | Specifies if output should be formatted | false |
Example
Request body:
{
"name" : "John",
"surname" : "Doe"
}
Template:
{{jsonPath req.body path='$.name'}}
Rendered response body:
John
XPath Helper¶
{{xPath <value> path='<path>'}}
- Evaluates XPath expression. XPath can be used to navigate through elements and attributes in an XML document.
This helper allows extracting data from the XML request body. See more about XPath.
Parameter | Description | Default value |
---|---|---|
path | Valid XPath expression Tester. If path is incorrect empty string will be returned. | none |
Example
Request body:
<bookstore name="Sample store">
<book><title>Title 1</title><size>1</size></book>
<book><title>Title 2</title><size>2</size></book>
</bookstore>
Template:
{{xPath req.body path='/bookstore/@name'}}
Rendered response body:
Sample store
Conditional Helpers¶
All listed Conditional Helpers are provided by Java implementation of Handlebard by jknack.
eq
- Test if two elements are equal.
Example
Request headers:
Token: invalid
Template:
{{#eq req.headers.[Token] 'valid'}}
Token is valid
{{else}}
Token is invalid
{{/eq}}
Rendered response body:
Token is invalid
neq
- Test if two elements are NOT equal.
Example
Request headers:
Token: invalid
Template:
{{#neq req.headers.[Token] 'valid'}}
Token is invalid
{{else}}
Token is valid
{{/neq}}
Rendered response body:
Token is invalid
gt
- Greater operator arguments must be comparable elements.
gte
- Greater or equal operator arguments must be comparable elements.
lt
- Less than operator arguments must be comparable elements.
lte
- Less than or equal operator arguments must be comparable elements.
Please note that headers, query parameters, and cookies are string values. Comparison of them is made lexicographically.
Example
Request headers:
Leter: f
Template:
{{#gt req.headers.[Letter] 'g'}}
Letter is invalid
{{else}}
Letter is valid
{{/gt}}
Rendered response body:
Letter is valid
and
- AND operator. Arguments evaluate to true
when they are not empty.
or
- OR operator. Arguments evaluate to true
when they are not empty.
not
- NOT operator. Arguments evaluate to true
when they are not empty.
Example
Request headers:
Token1: t1
Token2: t2
Template:
{{#and req.headers.[Token1].[0] req.headers.[Token2].[0]}}
Both tokens present
{{else}}
One or more tokens missing
{{/and}}
Rendered response body:
Both tokens present
Assignment Helper¶
Assignment Helper is provided by Java implementation of Handlebard by jknack.
{{#assign '<varName>'}}<expression>{{/assign}}
- Creates auxiliary variable (varName
) in current context and assigns an output of internal expression
to that variable.
This helper may be used to simplify templates that require complex helpers' compositions.
Example
Request body:
{"name" : "John", "surname": "Doe"}
Template:
{{#assign 'name'}}
{{jsonPath req.body path='$.name'}}
{{/assign}}
{{name}}
Rendered response body:
John
Accessing State¶
{{state.[Key].[Subkey].[index]}}
- Retrieve a value from current state of workspace. State may be initialized in Dynamic Mocks.
Please note that access to nested object is done through the '.[Key]' operator. If a value does not exist under a given key, an empty string is returned.
See more about state.
Example
State:
{
"people":
[
{"name" : "John", "surname": "Doe"},
{"name" : "Eric", surname: "Jackson"}
]
}
Template:
{{state.[people].[0].[name]}} {{state.[people].[0].[surname]}}
Rendered response body:
John Doe
Escaping Characters¶
In some cases, some of the helper's parameters may need special characters like '. To escape single quotes in helper parameters, use the '\' character. For example, if one would like to format a time so there is as 'at' string between the date and time, the helper definition would look as follows:
{{now format='yyyy-MM-dd\' at \'HH:mm:ssX' offset='-1 hours' timezone='UTC'}}
SmartMock.io HTML escapes values returned by an {{expression}}. If you don't want Handlebars to escape a value, use the "triple-stash", {{{.