RandomAPI

HomePricingDocumentationBlogLoginSign Up

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 Code
api.age      = random.numeric(1, 25);
api.dogYears = api.age * 7;
Result
{"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.

API Code
// 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('');
}
Result
{
  "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.

ModeArgumentsExample
numericmin, max
random.numeric(25, 85);    // 31
random.numeric('adsf', 2); // TypeError: Non numeric arguments provided
random.numeric(3, 2);      // RangeError: min is greater than max
specialmode, length
// Available predefined charsets
// 1: abcdef1234567890
// 2: ABCDEF1234567890
// 3: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890
// 4: 0123456789
// 5: abcdefghijklmnopqrstuvwxyz
// 6: ABCDEFGHIJKLMNOPQRSTUVWXYZ
// 7: abcdefghijklmnopqrstuvwxyz1234567890
// 8: ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890

random.special(1, 10); // 616283c380
random.special(2, 10); // 18550F0761
random.special(3, 10); // oyE8seFUJW
random.special(4, 10); // 3064867594
random.special(5, 10); // pvdsmelnei
random.special(6, 10); // YIHHSSVRXR
random.special(7, 10); // auws4syf9k
random.special(8, 10); // SEFXPCCBIP
customcharset, length
random.custom("1111111112", 10); // 1112111111
random.custom("aBcáΩßDefG1290é\"", 10); // G"BcGé02D1
random.custom("œ∑´®†¥¨ˆøπåß∂ƒ©˙∆˚¬Ω≈ç√∫˜µ", 10); // ®®ø˚øƒ˚†Ωç
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.

ModeArgumentsExample
ListlistRef, [lineNumber]
// list a1b2c3 contents:
// line 1: cat
// line 2: horse
// line 3: dog

list('a1b2c3'); // dog
list('a1b2c3', 2); // horse
Notice: Example 2 chose line number 2 from list a1b2c3.
Arrayarray, [indexNumber]
list(['a', 'b', 'c']); // c
list(["male", "female"], 1); // female
Warning: Indexes are zero based for arrays.
hash

Generate a hash from a string.

ModeArgumentsExample
md5str
// 82961fecf4f7ee8d8a10390072332efd
hash.md5('mysoupersekurepasswurd!');
sha1str
// 7babf75100bbe01ad3e0795831463dd9fd0ed517
hash.sha1('mysoupersekurepasswurd!');
sha256str
// a6360b34e354384e75de6241ba4fa3a33c6ef799c8943a04d000f19cb6af1051
hash.sha256('mysoupersekurepasswurd!');
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 Code
api.max = Number(getVar("max")) || 10;
api.num = random.numeric(0, api.max);
Result
// 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 Code
api.seed    = getVar('seed');
api.numSeed = getVar('numericSeed');
api.format  = getVar('fmt');
api.key     = getVar('key');
api.ref     = getVar('ref');
Result
{
  "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 Code
api.a = prng();
Result
{
  "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:

API Code
const faker = require('faker');
api.name    = faker.name.findName();
Result
{"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
Coding a snippet
// 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();
};
Using a snippet
const keith = require('keith/keiths stuff');
api.phone   = keith.phoneNumber();
api.name    = keith.randomName();

// Also works
api.phone2  = require('keith/keiths stuff/1').phoneNumber();
Result
{
  "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.

Coding a snippet
// invoice number generator
const moment = require('moment');
snippet = function() {
    return `${moment().format('YYMMDD')}-${random.special(6, 3)}-${random.special(4,5)}`;
};
Using a snippet
const invoice = require('keith/invoice number generator');
api.invoiceID = invoice();
Result
{
  "invoiceID": "160710-SIO-97604"
}

You can also access snippet properties straight from the require statement if you want.

Coding a snippet
// randomNum...kinda redundant
snippet.randomNum = (min, max) => random.numeric(min, max);
Using a snippet
const randomNum = require('keith/randomNum').randomNum;
api.a = randomNum();
Result
{
  "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.
    1. This is to prevent other users' APIs from breaking unexpectedly. Make sure that you really want to publish a snippet before you click confirm.
  • Published snippets will be given a revision number that starts at 1.
    1. 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();
  • 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.
    1. 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

ParameterDefault valueExample valueDescription
keynullABCD-1234-EFGH-5678(required) Your API Key
refnull1234abcd(required) The Ref ID of the API that you want to access
fmtjsonjson, pretty/prettyjson, csv, xml, yaml, raw, prettyrawFormat your data to your liking
  • json - Standard JSON object
  • pretty/prettyjson - Formatted JSON object to increase readability
  • csv - Standard CSV format
  • xml - Standard XML format
  • yaml - Standard YAML format
  • raw - Only output the generated contents (no results or info array included in output).
  • prettyraw - Same as raw with prettyjson applied to output
results1020How many results would you like to have generated
seedRandom 16 character hex stringhuskiesarecuteGenerate the same results
page13Pagination through results
hideuserinfonullNo value requiredRemove the user segment from the info property
noinfonullNo value requiredOnly show the results. Don't show the info property
dlnullNo value requiredDownload the file with proper headers and file extension
sole/onlyonenullNo value requiredThe 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 CodeHTTP CodeDescription
MISSING_API_KEY404The 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_REF404The 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_API404The API ref that was provided was not found.
INVALID_API_HASH404The API public hash that was provided was not found.
API_QUOTA_EXCEEDED403You'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_KEY401The API key that was provided was invalid. API keys are case-insensitive, however, the dashes are required.
UNAUTHORIZED_USER401Your API key does not have the proper permissions to access this API.
GENERATOR_OFFLINE500Something bad has happened and the generator has crashed. Please let us know by sending us a tweet or DM @RandomAPI.