Documentation
Learn how to code your API
General
If you know Javascript, then coding an API is a piece of cake! If not, it's fairly easy to pick up and is very similar to other programming languages. Check out this curated list of the world's best Javascript courses if you'd like an intro to the language and then check back here, we'll wait. :)
The reason you need to know Javascript is because APIs are coded in Javascript! No learning a new language and its fancy syntax required!
API Object
In RandomAPI, all of your fields are attached to the api object. A field is a Javascript property that holds the data that you want to generate and the api object is the central variable that RandomAPI will end up pushing into a results array.
api.age = random.numeric(1, 25);
api.dogYears = api.age * 7;
{"results":[{"age":20,"dogYears":140}]}
Variables and functions and comments, oh my!
Since APIs are coded in Javascript, you are free to do whatever you like in order to generate your data. This includes creating functions, variables, comments, etc. Just make sure that whatever data you generate gets attached to the api object or else it won't be available in your results.
// This is a comment that isn't evaluated
/*
Multiline comments work as well!
*/
const fullName = "Billy Builder"; // Not attached to api object
var middleName = "The";
let age = 5;
api.age = age; // Attached to api object
api.phone = phoneNum(); // Calling user defined function
function phoneNum(format) {
format = format || "(xxx) xxx-xxxx";
return String(format).split('').map(digit => {
return digit === 'x' ? random.numeric(0, 9) : digit;
}).join('');
}
{
"results": [
{
"age": 5,
"phone": "(336) 580-1131"
}
]
}
Sandbox
In order to keep other users and the server safe from malicious code, all APIs are executed in a sandboxed environment in a seperate process with limited native Node.js/Javascript functions available. Features like requiring native built-in modules, spawning child processes, access the file system, etc. are all disabled. All code is run in strict mode as well.
Native methods and built-in objects such as type casting using String and Number and using JSON.stringify are enabled and methods that can be chained to those data types such as .toString() are also available for use.
Available functions
RandomAPI includes some basic data generation functions that your API can make use of. All of these included functions respect the seed value that is sent in through an API request (except for timestamp since it returns the current time).
random
Generates a random number within a range as well as a string of random characters from a predefined or custom charset.
Mode | Arguments | Example | ||||
---|---|---|---|---|---|---|
numeric | min, max |
| ||||
special | mode, length |
| ||||
custom | charset, length | Notice: There is a 10% chance of a 2 being chosen in example 1. |
list
Chooses a random (or specified) item from either a list or provided array (inline list). If no lineNumber or indexNumber is provided, a random item will be chosen from the list or array respectively.
Mode | Arguments | Example | |
---|---|---|---|
List | listRef, [lineNumber] | Notice: Example 2 chose line number 2 from list a1b2c3. | |
Array | array, [indexNumber] | Warning: Indexes are zero based for arrays. |
hash
Generate a hash from a string.
Mode | Arguments | Example | ||||
---|---|---|---|---|---|---|
md5 | str |
| ||||
sha1 | str |
| ||||
sha256 | str |
|
timestamp
Returns the current unix timestamp.
timestamp(); //
getVar
Fetches the value of GET variables in the API query. Defaults to null if the requested GET variable is undefined.
api.max = Number(getVar("max")) || 10;
api.num = random.numeric(0, api.max);
// https://randomapi.com//api/123456?max=25
{"results":[{"max": 100,"num": 21}]}
// https://randomapi.com//api/123456
{"results":[{"max": 10,"num": 4}]}
You can also access some internal variables as well with getVar. This could be useful if you wanted access to the string/numeric seed that the generator is using or maybe wanted to know the format your API was being requested with.
api.seed = getVar('seed');
api.numSeed = getVar('numericSeed');
api.format = getVar('fmt');
api.key = getVar('key');
api.ref = getVar('ref');
{
"results": [
{
"seed": "7583c1fdce1943f4",
"numericSeed": 4200665598,
"format": "pretty",
"key": "ABCD-1234-EFGH-5678",
"ref": "1234abcd"
}
]
}
Misc
Some other good to know things regarding the generator.
- The generator uses internal variables that start with _API, so avoid using variables in that namespace if you can or else unexpected behavior can happen.
If you have made an API/Snippet that requires a PRNG, you can access the generator's internal PRNG with the prng function. This will return, direct from the Mersenne Twister module the generator is using, a number on the [0,1) real interval.
api.a = prng();
{
"results": [
{
"a": 0.5300652552396059
}
]
}
Global Snippets
While native, built-in modules aren't accessible through require, some libraries that we have found helpful for generating data will be added to the RandomAPI generators for use in your APIs. Currently, the following modules are available using require:
const faker = require('faker');
api.name = faker.name.findName();
{"results":[{"name": "Samir Daugherty"}]}
If you have a suggestion for a module that we should add, send us a tweet or DM @RandomAPI.
Snippets
Snippets are user defined pieces of code that you can include in your API. If you've made a snippet that you'd like to share for others to use, you can publish your 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.
Coding
// keiths stuff
const faker = require('faker');
// phoneNumber property attached to snippet
snippet.phoneNumber = function(format) {
format = format || "(xxx) xxx-xxxx";
return String(format).split('').map(digit => {
return digit === 'x' ? random.numeric(0, 9) : digit;
}).join('');
};
// randomName property attached to snippet
snippet.randomName = function() {
return faker.name.findName();
};
const keith = require('keith/keiths stuff');
api.phone = keith.phoneNumber();
api.name = keith.randomName();
// Also works
api.phone2 = require('keith/keiths stuff/1').phoneNumber();
{
"phoneNumber": "(605) 401-1008",
"randomName": "Nadia Johns"
}
If you only want to have one snippet, you can make a default snippet by overriding the snippet object.
// invoice number generator
const moment = require('moment');
snippet = function() {
return `${moment().format('YYMMDD')}-${random.special(6, 3)}-${random.special(4,5)}`;
};
const invoice = require('keith/invoice number generator');
api.invoiceID = invoice();
{
"invoiceID": "160710-SIO-97604"
}
You can also access snippet properties straight from the require statement if you want.
// randomNum...kinda redundant
snippet.randomNum = (min, max) => random.numeric(min, max);
const randomNum = require('keith/randomNum').randomNum;
api.a = randomNum();
{
"num": 37
}
Publishing
If you've made an awesome snippet that you think would be useful for others, you can publish it!
Here are some basic rules and tips on publishing snippets:
- Once published, snippets can not be removed.
- Published snippets will be given a revision number that starts at 1.
- Source code of revisions that are published can not be modified. You can still modify the revision's description though as well as the snippet's tags, but the snippet name cannot be modified once it is published to avoid confusion between revisions.
- If you have made a mistake or want to make an improvement to a snippet, you can create a new revision.
- Users can search for snippets by clicking the search menu item.
- This is to prevent other users' APIs from breaking unexpectedly. Make sure that you really want to publish a snippet before you click confirm.
- Once a snippet is published, you must provide a revision number in the snippet signature when you use the require function.
const r1 = require('keith/randomNum/1').randomNum; // Revision 1
const r2 = require('keith/randomNum/4').randomNum; // Revision 4
const r3 = require('keith/randomNum').randomNum; // Won't work if snippet is published
api.a = r1();
api.b = r2();
- Search depends on the tags/keywords that you give a snippet. Make sure that you provide good tags that users will most likely search for in order to have the best chance of your snippet being found.
Calling APIs
APIs can be accessed via the https://randomapi.com/api endpoint.
At a minimum, the endpoint requires a key and ref value or a public hash value. Key would be your API key and ref is the Ref ID of the API you want to access which can be found on the View APIs page.
Public hashes are another way that you can access your API without accidentally exposing your API Key and API Ref ID. The user segment of the info block from your results will also be removed by default when your API is called using this method. They can be found by clicking Run API (public URL) on the View APIs page.
APIs can be called in three different ways:
https://randomapi.com/api/1234abcd?key=ABCD-1234-EFGH-5678 // Ref value is implied
https://randomapi.com/api/?key=ABCD-1234-EFGH-5678&ref=1234abcd // Ref value is explicitly stated
https://randomapi.com/api/1234567890abcdef1234567890abcdef // Public hash
Options
You can add extra parameters to your API call to transform your data into different formats, specify how many results you'd like to generate, specify a seed, and even communicate with your api through the getVar function
Parameter | Default value | Example value | Description | |
---|---|---|---|---|
key | null | ABCD-1234-EFGH-5678 | (required) Your API Key | |
ref | null | 1234abcd | (required) The Ref ID of the API that you want to access | |
fmt | json | json, pretty/prettyjson, csv, xml, yaml, raw, prettyraw | Format your data to your liking | |
| ||||
results | 10 | 20 | How many results would you like to have generated | |
seed | Random 16 character hex string | huskiesarecute | Generate the same results | |
page | 1 | 3 | Pagination through results | |
hideuserinfo | null | No value required | Remove the user segment from the info property | |
noinfo | null | No value required | Only show the results. Don't show the info property | |
dl | null | No value required | Download the file with proper headers and file extension | |
sole/onlyone | null | No value required | The results array will choose the 1st result. Good to use together with the raw/prettyraw format if your API is only going to only generate 1 result. If the results option is set, it'll be overridden to 1 when used with this option. |
https://randomapi.com/api/1234abcd?key=ABCD-1234-EFGH-5678&results=25&seed=huskiesarecute&page=3
https://randomapi.com/api/?key=ABCD-1234-EFGH-5678&ref=1234abcd&callback=fetchData
https://randomapi.com/api/?key=ABCD-1234-EFGH-5678&ref=1234abcd&fmt=xml&dl
https://randomapi.com/api/?key=ABCD-1234-EFGH-5678&ref=1234abcd&fmt=pretty&noinfo
Errors
Error Code | HTTP Code | Description | ||||
---|---|---|---|---|---|---|
MISSING_API_KEY | 404 | The API call could not be complete since an API key was not provided. Make sure you include your key with the key parameter. | ||||
MISSING_API_REF | 404 | The API call could not be complete since an API ref was not provided. Make sure you include your ref with the ref parameter or specify it in the URI after /api/REF_KEY. | ||||
INVALID_API | 404 | The API ref that was provided was not found. | ||||
INVALID_API_HASH | 404 | The API public hash that was provided was not found. | ||||
API_QUOTA_EXCEEDED | 403 | You've used up your daily number of results. Please upgrade or wait until your quota resets at midnight in the timezone you selected when you signed up. | ||||
INVALID_API_KEY | 401 | The API key that was provided was invalid. API keys are case-insensitive, however, the dashes are required. | ||||
UNAUTHORIZED_USER | 401 | Your API key does not have the proper permissions to access this API. | ||||
GENERATOR_OFFLINE | 500 | Something bad has happened and the generator has crashed. Please let us know by sending us a tweet or DM @RandomAPI. |