What is a Snippet?
A snippet is a user-defined piece of code that can be included in your API. If you've made a function that you think could be helpful to others, you can share your snippet by publishing it for others to search for! Think of it like node modules for NPM.
Snippets are also useful for organizing your code/APIs. If you use a piece of code often in many of your APIs, you could make a private snippet and then reference the snippet in your APIs to save space and make your code more readable.
From this
api.phone = phoneNum();
function phoneNum(format) {
format = format || "(xxx) xxx-xxxx";
return String(format).split('').map(digit => {
return digit === 'x' ? random.numeric(0, 9) : digit;
}).join('');
}
To this
const phoneNum = require('~phoneNum');
api.phone = phoneNum();
To make the above snippet, I made a new snippet called "phoneNum" and assigned my function to the variable snippet
. Snippets are coded in basically the same way as a normal API except for these key differences:
- Objects are attached to the snippet object instead of the api object.
- Only Global Snippets can be used in your snippet. You can't require other snippets from your snippet.
- Snippet names must be unique in regards to your account (you can't have two snippets named "phonenum" for example).
- Only inline lists can be used in your API.
snippet = function(format) {
format = format || "(xxx) xxx-xxxx";
return String(format).split('').map(digit => {
return digit === 'x' ? random.numeric(0, 9) : digit;
}).join('');
};
In the phone number example above, I attached my function directly to the snippet object kind of like what we did at the end of the What is an API blog post. But, you also have the option to attach multiple functions to a snippet as different properties. You can then access those snippet functions using their property names.
mysnippet
snippet.a = function() {
return "a";
};
snippet.b = function() {
return "b";
};
snippet.randomHexLetter = function() {
return list(['a', 'b', 'c', 'd', 'e', 'f']);
};
This snippet is pretty useless, but you can imagine the power that snippets have when used in conjunction with other snippets in your API.
To access the snippet functions above, you'd use the require
function.
const mysnippet = require('~mysnippet');
api.a = mysnippet.a();
api.b = mysnippet.b();
api.hex = mysnippet.randomHexLetter();
{
"a": "a",
"b": "b",
"hex": "d"
}
You can also access snippets directly from the require function if you only need to use it once.
api.a = require('~mysnippet').a();