Template Usage
Example - Create a mock api
You can create a static or dynamic mock api easily in template. Just define module.exports
with the data you want to receive.
module.exports = {
success: true,
result: [
{
id: 1,
name: 'User 1',
},
{
id: 2,
name: 'User 2',
},
{
id: 3,
name: 'User 3',
},
],
};
- Response of
https://api.collectapi.com/run/test/5c7fc42dc78c3447d49f1cc3
{
"success": true,
"result": [
{
"name": "User 1",
"id": 1
},
{
"name": "User 2",
"id": 2
},
{
"name": "User 3",
"id": 3
}
]
}
Example - Create a mock login api
In this example we'll create a mock login api. We'll create a custom javascript function validate our request and return a response.
To connect javascript with template we just need to call it from inside of template with __js('login(item)')
. Here item(cursor) would be our request body.
// username: password
const users = {
admin: 'admin',
testuser: 'test123',
};
// Our logic function
function login(body) {
let { username, password } = body;
if (!username || !password) return { success: false, message: 'Username and Password is required..!' };
if (users[username] && users[username] === password) return { success: true, message: 'Hello ' + username };
else return { success: false, message: 'Username or Password is invalid..!' };
}
// Our template code to call login function and return the result.
module.exports = __js('login(item)');
- Try #1
curl -X POST \
https://api.collectapi.com/run/test/5c7fc515dfb65f48c06bc2f0 \
-H 'Content-Type: application/json' \
-d '{}'
{
"success": false,
"message": "Username and Password is required..!"
}
- Try #2
curl -X POST \
https://api.collectapi.com/run/test/5c7fc515dfb65f48c06bc2f0 \
-H 'Content-Type: application/json' \
-d '{
"username": "admin",
"password": "test"
}'
{
"success": false,
"message": "Username or Password is invalid..!"
}
- Try #3
curl -X POST \
https://api.collectapi.com/run/test/5c7fc515dfb65f48c06bc2f0 \
-H 'Content-Type: application/json' \
-d '{
"username": "admin",
"password": "admin"
}'
{
"success": true,
"message": "Hello admin"
}
Login example with Helpers
This is the same login example written with helpers.
// username: password
const users = {
admin: 'admin',
testuser: 'test123',
};
// Our template code with base helpers.
module.exports = {
__if: '!item.username || !item.password',
__then: { success: false, message: 'Username and Password is required..!' },
__else: {
__if: 'users[item.username] && users[item.username] === item.password',
__then: { success: true, message: 'Hello {{username}}' },
__else: { success: false, message: 'Username or Password is invalid..!' },
},
};
- Response of
https://api.collectapi.com/run/test/5c80d30d261ef047d9c2d40c?username=admin&password=admin
{
"success": true,
"message": "Hello admin"
}
Example - Use external services
In this example we'll use a open-source mock user generator api https://randomuser.me/. We'll use https://randomuser.me/api/
endpoint to generate random user and transform the response to our desired json format.
For more information about randomuser api please visit their website at https://randomuser.me/.
module.exports = {
__request: {
uri: 'https://randomuser.me/api/?results=5&seed=collectapi',
then: {
__each: 'results',
id: '{{login.uuid}}',
name: '{{name.first}} {{name.last}}',
email: '{{email}}',
username: '{{login.username}}',
image: '{{picture.large}}',
gender: '{{gender}}',
},
},
};
- Response of
https://api.collectapi.com/run/test/5c7fcb3b261ef047d9c2d3ee
[
{
"id": "c861e546-141a-4242-b33e-54e8dc1bf308",
"name": "pablo leclercq",
"email": "[email protected]",
"username": "bluetiger396",
"image": "https://randomuser.me/api/portraits/men/50.jpg",
"gender": "male"
},
{
"id": "d7064ffe-6b38-4fe0-9352-2998cfa7d63a",
"name": "angel morales",
"email": "[email protected]",
"username": "angryswan786",
"image": "https://randomuser.me/api/portraits/men/22.jpg",
"gender": "male"
},
{
"id": "9410dc7b-3b3d-4727-8682-8b1e6690ae82",
"name": "tiril oppegård",
"email": "tiril.oppegå[email protected]",
"username": "redduck479",
"image": "https://randomuser.me/api/portraits/women/18.jpg",
"gender": "female"
},
{
"id": "0c9ea62f-fba5-43fe-93ca-59a36ac39cd0",
"name": "clayton wells",
"email": "[email protected]",
"username": "blackkoala869",
"image": "https://randomuser.me/api/portraits/men/22.jpg",
"gender": "male"
},
{
"id": "3857f0d9-df63-48f4-af68-d9fbe5c785c3",
"name": "deniz öymen",
"email": "deniz.ö[email protected]",
"username": "purplebutterfly838",
"image": "https://randomuser.me/api/portraits/women/48.jpg",
"gender": "female"
}
]
Example - Create api from HTML
In this example we'll parse a html response and retieve desired paramaters from webpage.
module.exports = {
__request: {
uri: 'https://www.bbc.co.uk/search?q=world&filter=news',
then: {
__html: {
__each: '.search-results > li',
__limit: 5,
title: '{{h1}}',
url: "{{$ $('h1 a',item).attr('href') }}",
image: "{{$ $('img',item).attr('src') }}",
},
},
},
};
- Results of
https://api.collectapi.com/run/test/5c7fd0bd261ef047d9c2d3f5
[
{
"title": "One-minute World News",
"url": "https://www.bbc.co.uk/news/10462520",
"image": "https://ichef.bbci.co.uk/news/384/cpsprodpb/15C7E/production/_90041298_p01tlf61.jpg"
},
{
"title": "BBC World News business headlines",
"url": "https://www.bbc.co.uk/news/business-11876811",
"image": "https://ichef.bbci.co.uk/news/384/mcs/media/images/66951000/jpg/_66951438_biz_heads_640x360_with_logo.jpg"
},
{
"title": "Bugatti unveils the world's most expensive new car",
"url": "https://www.bbc.co.uk/news/business-47469562",
"image": "https://ichef.bbci.co.uk/news/384/cpsprodpb/04D9/production/_105914210_gettyimages-1133970604-594x594.jpg"
},
{
"title": "Huawei: The world's most controversial company?",
"url": "https://www.bbc.co.uk/news/business-47465142",
"image": "https://ichef.bbci.co.uk/news/384/cpsprodpb/123E/production/_105907640_huawei.jpg"
},
{
"title": "Kylie Jenner becomes world's youngest billionaire",
"url": "https://www.bbc.co.uk/news/business-47455998",
"image": "https://ichef.bbci.co.uk/news/384/cpsprodpb/2042/production/_102685280_gettyimages-956294722.jpg"
}
]
Now our template is working correctly we can add dynamic query to search. Instead of static world we'll put {{query}}
in __request.uri section. This will try to read query value from request body/query.
module.exports = {
__request: {
uri: 'https://www.bbc.co.uk/search?q={{query}}&filter=news',
then: {
__html: {
__each: '.search-results > li',
__limit: 5,
title: '{{h1}}',
url: "{{$$('h1 a',item).attr('href')}}",
image: "{{$$('img',item).attr('src')}}",
},
},
},
};
- Result of
https://api.collectapi.com/run/test/5c80c418dfb65f48c06bc30b?query=earthquake
[
{
"title": "Surrey earthquake 'shakes houses'",
"url": "https://www.bbc.co.uk/news/uk-england-47383611",
"image": "https://ichef.bbci.co.uk/news/384/cpsprodpb/6BBD/production/_105818572_earthquake.jpg"
},
{
"title": "Independent Group: Minor tremor or political earthquake?",
"url": "https://www.bbc.co.uk/news/uk-politics-47307038",
"image": "https://ichef.bbci.co.uk/news/384/cpsprodpb/EE60/production/_105742016_iginparliament.jpg"
},
{
"title": "Surrey hit by another earthquake",
"url": "https://www.bbc.co.uk/news/uk-england-47239242",
"image": "https://ichef.bbci.co.uk/news/384/cpsprodpb/2034/production/_105644280_bgs_quake_140219.jpg"
},
{
"title": "Alaska hit by earthquake",
"url": "https://www.bbc.co.uk/news/world-us-canada-46408158",
"image": "https://ichef.bbci.co.uk/news/384/cpsprodpb/EB07/production/_104576106_p06tc1dx.jpg"
},
{
"title": "Firefighters revisit the scene of Armenia's earthquake in 1988.",
"url": "https://www.bbc.co.uk/news/world-europe-46634593",
"image": "https://ichef.bbci.co.uk/news/384/cpsprodpb/A849/production/_104918034_p06wbb4p.jpg"
}
]
Example - Use of moment.js and lodash
We can use lodash, moment and other Accessible Libraries
from inside __js
helper, {{$}}
blocks or outside.
But if we want to access request body we need to use it from __js
or {{$}}
block or we need to call a defined function.
const list = _.range(0, 10); // [0,1,2,3,4,5,6,7,8,9]
const createDate = item =>
_.map(_.range(0, item.max), count =>
moment()
.add(count, 'days')
.locale('en')
.format('LLL')
);
module.exports = {
success: true,
max: '{{$ _.map(list, x=> x * item.max) }}',
filtered: __js('_.filter(list, x=> x < item.max)'),
dates: __js('createDate(item)'),
};
- Response of
https://api.collectapi.com/run/test/5c80d465dfb65f48c06bc311?max=5
{
"success": true,
"max": "0,5,10,15,20,25,30,35,40,45",
"filtered": [0, 1, 2, 3, 4],
"dates": ["March 7, 2019 9:35 AM", "March 8, 2019 9:35 AM", "March 9, 2019 9:35 AM", "March 10, 2019 9:35 AM", "March 11, 2019 9:35 AM"]
}
Example - Edit scope and item(cursor)
In this example we use __js
to run and modify our cursor. __js
helper would change cursor with the value received from the javascript code from the first argument and run the second argument as template code.
Here fill function try to find the user data from lib object and return it's value. Also we modify scope and put data object in it.
You don't need to access modified scope value from inside __js
run. Here template tries to access {{#data.username}}
before and after __js
run. But only after code line runned we can access scope.data.username.
const lib = {
admin: 'Pw123',
adam: 'adampw'
};
function fill(body, scope) {
let password = body.user && lib[body.user];
scope.data = { username: body.user, password: password };
return { success: !!password };
}
module.exports = {
before: '{{user}}: {{#data.username}}',
code: __js('fill(item,scope)', {
success: __js('item.success'),
result: {
__if: 'item.success',
__then: __js('scope.data'),
__else: "User '{{#body.user}}' could't found."
}
}),
after: '{{user}}: {{#data.username}}'
};
- Response of
https://api.collectapi.com/run/test/5c80ef63261ef047d9c2d414?user=adam
{
"before": "adam:",
"code": {
"success": true,
"result": {
"username": "adam",
"password": "adampw"
}
},
"after": "adam: adam"
}
- Response of
https://api.collectapi.com/run/test/5c80ef63261ef047d9c2d414?user=test
{
"before": "test:",
"code": {
"success": false,
"result": "User 'test' could't found."
},
"after": "test: test"
}