Templating in Response Body
Beeceptor implements Handlerbars to provide dynamic mocked responses. This helps a mocking rule to utilize attributes from request payload and query parameters to generate a dynamic response.
This feature is available with paid plans and takes the API mocking experience near to realistic.
Using Templates in Response Body
Beeceptor parses incoming request for request payload and query parameters as a JSON objects. This objects are available to template engine to be substituted response. Here are a few facts you should know before you start using this.
- The template engine uses Handlerbars's syntax.
- By default, template engine is off. You need to explicitly mark a rule to enable usage of Handlebars template.
A handlebars expression is enclosed between {{
and }}
. When the template is executed, these expressions are replaced with values from a request object. Beeceptor uses special Handlebars helpers to extract request parameters.
When there are syntax errors in defining templates, Beeceptor tries to recover safely and attempts to generate the mocked response. If there are unrecoverable errors, a response with 561
status code is returned. In such cases, you should review the template syntax and correct it.
Request Payload Helpers
These helpers allow you to pick any request parameter and send in mocked response.
Syntax
Beeceptor supports following two types of template helpers to extract request parameters and add to mocked response. The request payload is parsed only if the entering Content-Type
is set to one of below.
- JSON payload -
application/json
- Form URL encoded -
application/x-www-form-urlencoded
Helper Name | Description & syntax |
---|---|
body | Extracts request payload/body from either JSON or Form URL Encoded. Both of these are built into JSON object to be used in template. This typically works for POST , PATCH and PUT types of HTTP verbs.Syntax: {{body 'path' 'default-value'}} |
queryParam | Extracts query parameters and builds a JSON object to be used in template. This works for all HTTP verbs. Syntax: {{queryParam 'path' 'default-value'}} |
Parameter details:
- The
path
is a required parameter in the above syntax. - The
default-value
is optional, falls back to empty string. - The
path
parameter allows accessing deep properties using a flat representation string. Some examples arekeyName
,parent.child
,keyName.1.childKey
. This works for JSON Objects and JSON Arrays as object roots. - If no value is found corresponding to given
path
, thedefault-value
is returned.
Example
Consider a following example with mocking rule and request payload:
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'}}"
}
Request: Request payload entering with application/json
content-type
at server path /my-rule?type=individual
{
"address": "80, Pearl Residency, MG Road, India",
"age": 99,
"name": {"first": "Arti", "last": "Jain"}
}
Response: Beeceptor will generate following response body. Here individual
is picked from query parameter and rest from the JSON request payload.
{
"type": "individual",
"address": "80, Pearl Residency, MG Road, India",
"age": 99,
"full_name": "Arti - Jain"
}
Fake Data Helpers
Fake data is frequently needed. You need it during development, testing, demonstrations and training situations.
Beeceptor uses popular faker.js's comparable syntax. It becomes a breeze to generate small/large data using a mocked response template. You can use pretty much all the attributes from faker.js namespaces.
Syntax
Beeceptor defines faker
as Handlerbars template helper.
Syntax:
{{faker 'namespace.attribute'}}
Faker.js attributes are grouped into namespaces. E.g. random
, address
, company
, etc. To generate faked value for given attribute, prefix the attribute with its namespace. Refer below examples and values generated.
Sample Syntax | Generated value |
---|---|
{{faker 'random.uuid'}} | 52375efe-cf9e-44f5-adb2-65c1631bfcea |
{{faker 'address.country'}} | Spain |
{{faker 'finance.currencyCode'}} | USD |
{{faker 'hacker.phrase'}} | The AI hard drive is down, index the 1080p panel so we can override the COM firewall! |
{{faker 'lorem.paragraph'}} | Omnis perspiciatis provident error. Est possimus voluptates. Illo nam et excepturi blanditiis quae rerum et amet accusantium. Mollitia temporibus temporibus ea fugiat quia in possimus et. Ut provident est debitis perspiciatis ipsa non mollitia magnam quis. Et quod dolorum et non |
Refer the section below to view complete list of supported attributes.
Example
You can mix and match any of the faker attributes to build a rich response. Consider the following example for GET /users
API or model.
Mocking Template: A mocking template to build user objects.
[
{
"id" : "{{faker 'random.uuid'}}",
"name": "{{faker 'name.firstName'}} {{faker 'name.lastName'}}" ,
"address": "{{faker 'address.streetAddress'}}",
"country": "{{faker 'address.country'}}",
"phone": "{{faker 'phone.phoneNumber'}}",
"profileImage": "{{faker 'image.image'}}",
},
{
"id" : "{{faker 'random.uuid'}}",
"name": "{{faker 'name.firstName'}} {{faker 'name.lastName'}}" ,
"address": "{{faker 'address.streetAddress'}}",
"country": "{{faker 'address.country'}}",
"phone": "{{faker 'phone.phoneNumber'}}",
"profileImage": "{{faker 'image.image'}}",
}
]
Response: This will generate below output:
[
{
"id" : "cbe55c5d-36fa-4f05-9557-fcd4966187f4",
"name": "Dillon Davis" ,
"address": "613 Dickinson Run",
"country": "Tanzania",
"phone": "886.282.3509 x0831",
"profileImage": "http://placeimg.com/640/480/business",
},
{
"id" : "36df51a8-8d4c-4d70-8818-d77b9f6bf215",
"name": "Dannie Hackett" ,
"address": "8449 Brenna Alley",
"country": "Central African Republic",
"phone": "(786) 895-4923",
"profileImage": "http://placeimg.com/640/480/business",
}
]
Supported Attributes
Random: To generate random numbers, id or other data.
random.number
random.uuid
random.boolean
random.word
random.words
random.image
random.locale
random.alphaNumeric
Lorem: Some blah blah... text and paragraphs.
lorem.word
lorem.words
lorem.sentence
lorem.slug
lorem.sentences
lorem.paragraph
lorem.paragraphs
lorem.text
lorem.lines
Person Names: Generate first/last name, titles, job type, etc.
name.firstName
name.lastName
name.findName
name.jobTitle
name.prefix
name.suffix
name.title
name.jobDescriptor
name.jobArea
name.jobType
Address
address.zipCode
address.city
address.cityPrefix
address.citySuffix
address.streetName
address.streetAddress
address.streetSuffix
address.streetPrefix
address.secondaryAddress
address.county
address.country
address.countryCode
address.state
address.stateAbbr
address.latitude
address.longitude
Phone Numbers:
phone.phoneNumber
phone.phoneNumberFormat
phone.phoneFormats
E-commerce: Some realistic product names.
commerce.color
commerce.department
commerce.productName
commerce.price
commerce.productAdjective
commerce.productMaterial
commerce.product
Company:
company.suffixes
company.companyName
company.companySuffix
company.catchPhrase
company.bs
company.catchPhraseAdjective
company.catchPhraseDescriptor
company.catchPhraseNoun
company.bsAdjective
company.bsBuzz
company.bsNoun
Finance:
finance.account
finance.accountName
finance.mask
finance.amount
finance.transactionType
finance.currencyCode
finance.currencyName
finance.currencySymbol
finance.bitcoinAddress
finance.iban
finance.bic
Date:
date.past
date.future
date.between
date.recent
date.month
date.weekday
Online Forum:
hacker.abbreviation
hacker.adjective
hacker.noun
hacker.verb
hacker.ingverb
hacker.phrase
Images: Generates links to images for the following categories.
E.g.
The image.animals
syntax will generate a link to http://placeimg.com/640/480/animals. The image.image
syntax will generate a link to a random image for any of the below categories.
image.image
image.avatar
image.imageUrl
image.abstract
image.animals
image.business
image.cats
image.city
image.food
image.nightlife
image.fashion
image.people
image.nature
image.sports
image.technics
image.transport
image.dataUri
Internet:
internet.avatar
internet.email
internet.exampleEmail
internet.userName
internet.protocol
internet.url
internet.domainName
internet.domainSuffix
internet.domainWord
internet.ip
internet.ipv6
internet.userAgent
internet.color
internet.mac
internet.password
Database:
database.column
database.type
database.collation
database.engine
Git:
git.branch
git.commitEntry
git.commitMessage
git.commitSha
git.shortSha
System:
system.fileName
system.commonFileName
system.mimeType
system.commonFileType
system.commonFileExt
system.fileType
system.fileExt
system.directoryPath
system.filePath
system.semver