Mockaroo APIs

Overview

Mockaroo offers two different approaches for downloading data programmatically:


Generate API

Mockaroo's Generate API is a single endpoint that you can use to generate data based on a saved schema or fields you define in the post body of the request. Anything you can generate via the website can also be generated via the data API.


Mock APIs

Mock APIs give your full control over URLs, handling request parameters, and simulating errors. Mock APIs are ideal for simulating back ends before they're built so you can start working on your front end code. Configure Mock APIs using the APIs link in the header.

Gaining Access

Both APIs require an API Key to be passed with each request, either as a query string parameter called "key" or as an "X-API-Key" request header.

Here is your API key:

You must be signed in to use the REST API.   Sign in

Usage Limits

All API requests are limited to 5000 records. Free plans are limited to 200 requests per day. Silver and Gold plans are limited to a total number of records per day (with no request limit). This allows developers with paid plans to issue many more small requests than would be allowed with a free plan.

PlanLimit
Free200 requests/day
Silver1,000,000 records/day
Gold10,000,000 records/day



Data API

The Mockaroo Data API has two methods:

/api/types.json

GET  https://api.mockaroo.com/api/types.json?key=(your API key)

Returns an array of the available types. Each object has the following keys:

  • name (string) - The name of the type
  • parameters (array) - Additional options that can be specified
    • name (string) - The parameter name
    • type (string) - The parameter type
    • description (string) - A description of the parameter
    • default (any) - The default value of the parameter if not specified

/api/generate(.format)

POST  https://api.mockaroo.com/api/generate(.format)?key=(your API key)

Generates data based on parameters you provide or a saved schema.

Formats

Output format is specified by the file type part of the URL. Two formats are supported:

FormatURLDescription
jsonhttps://api.mockaroo.com/api/generate.jsonResults are returned as a json object. Results will be returned as an array if the "size" query string parameter is greater than 1.
csvhttps://api.mockaroo.com/api/generate.csvComma separated values. The first row will contain the field names. Subsequent rows will contain the generated data values.
txthttps://api.mockaroo.com/api/generate.txtTab-separated values. The first row will contain the field names. Subsequent rows will contain the generated data values.
customhttps://api.mockaroo.com/api/generate.customSpecify a custom delimiter using the "delimiter" query parameter. Specify a custom quote character using the "quote_char" query parameter. The first row will contain the field names. Subsequent rows will contain the generated data values.
sqlhttps://api.mockaroo.com/api/generate.sqlResults are returned as SQL insert statements.
xmlhttps://api.mockaroo.com/api/generate.xmlResults are returned as an xml document.

Query String Parameters

ParameterTypeDescription
keystring(required) Your api key
callbackstring(optional) The name of a javascript function to call in the response. If specified, the response will be in jsonp format.
countinteger(optional) The number of rows to generate. Defaults to 1, or if a saved schema is used, the number of rows specified on the saved schema. When json format is requested, the result will be an object when size = 1, an array when size > 1. Free accounts are limited to 5000 records per download.
arrayboolean(optional) When generating json data, Mockaroo will return an array when count > 1 and an object when count is 1. To always return an array, specify a value of "true" for this parameter. Defaults to false.
include_nullsboolean(optional) When generating json data, Mockaroo will omit keys with null values if this is set to false.
include_headerboolean(optional) Only relevant for csv format. Set to false to omit the header row. Defaults to true.
schemastring(optional) The name of a saved schema to use. If this parameter is not specified, you must define the fields in the request body as specified below.
root_elementstring(optional, only used when format is xml) The name to give to the root element in the document
record_elementstring(optional, only used when format is xml) The name to give to each element representing a record
delimitercharacter(optional, only used when format is custom) The character to use as a column separator
quote_charcharacter(optional, only used when format is custom) The character to use when enclosing values. Defaults to double-quote.
line_endingstring(optional, only used when format is custom) "unix" or "windows"
bomboolean(optional, only used when format is csv, txt, or custom) true to include the BOM (byte order mark). Defaults to false.
fieldsjson array(optional) A json array of field specifications. See request body below for details. When using JSONP, you must specify fields using this URL parameter as JSONP does not allow the caller to pass data in the body of the request.

Request Body

If the schema url parameter is not specified, the request body should be a json array of field specifications. Each item in the array should have the following properties:

ParameterTypeDefaultDescription
namestringThe name of the field. When using json format, you can use "." in field names to generate nested json objects, brackets to generate arrays.   More information...
percentBlankinteger0An integer between 0 and 100 that determines what percent of the generated values will be null
formulastring0Alters the generated value using Mockaroo formula syntax. Use this to refer to the value of this field.
typestring
One of Mockaroo's 142 data types:

Animal Common Name
Animal Scientific Name
App Bundle ID
App Name
App Version
Base64 Image URL
Binomial Distribution
Bitcoin Address
Blank
Boolean
Buzzword
Car Make
Car Model
Car Model Year
Car VIN
Catch Phrase
City
Color
Company Name
Country Code
Credit Card #
Credit Card Type
Currency
Currency Code
Department (Corporate)
Department (Retail)
Domain Name
Drug Company
Drug Name (Brand)
Drug Name (Generic)
DUNS Number
EIN
Email Address
Encrypt
Fake Company Name
Family Name (Chinese)
FDA NDC Code
File Name
First Name
First Name (European)
First Name (Female)
First Name (Male)
Frequency
Full Name
Gender
Gender (abbrev)
Given Name (Chinese)
GUID
Hex Color
IBAN
ICD10 Diagnosis Code
ICD10 Dx Desc (Long)
ICD10 Dx Desc (Short)
ICD10 Proc Desc (Long)
ICD10 Proc Desc (Short)
ICD10 Procedure Code
ICD9 Diagnosis Code
ICD9 Dx Desc (Long)
ICD9 Dx Desc (Short)
ICD9 Proc Desc (Long)
ICD9 Proc Desc (Short)
ICD9 Procedure Code
IP Address v4
IP Address v4 CIDR
IP Address v6
IP Address v6 CIDR
ISBN
Job Title
Language
Last Name
Latitude
LinkedIn Skill
Longitude
MAC Address
MD5
MIME Type
MongoDB ObjectID
Movie Genres
Movie Title
Naughty String
NHS Number
Password
Plant Common Name
Plant Family
Plant Scientific Name
Postal Code
Product (Grocery)
Race
Row Number
SHA1
SHA256
Shirt Size
Short Hex Color
Slogan
SSN
Stock Industry
Stock Market
Stock Market Cap
Stock Name
Stock Sector
Stock Symbol
Street Address
Street Name
Street Number
Street Suffix
Suffix
Time Zone
Title
Top Level Domain
University
User Agent
Username

Type Specific Parameters

The following types have additional parameters:

ParameterTypeDefaultDescription
Avatar
heightintegerthe image height in pixels
widthintegerthe image height in pixels
Binomial
probabilitydecimal0.5The probability of success
Character Sequence
formatstringA string of characters, digits, and symbols
Country
countriesarrayAn array of countries to restrict the generated locations to
Custom List
valuesarrayAn array of values to pick from. Each value should be a string.
selectionStylestringrandomSee list distribution types.

Must be of the following:
  • random
  • sequential
  • custom
  • cartesian
Dataset Column
datasetstringThe name of a saved dataset
columnstringThe name of the column in the saved dataset
selectionStylestringrandomSee list distribution types.

Must be of the following:
  • random
  • sequential
  • custom
  • cartesian
Date
minstring7/19/2018The minimum date in mm/dd/yyyy format.
maxstring7/19/2017The maximum date in mm/dd/yyyy format.
formatstring%FT%T%:z(optional) The format to output. This can be any format directive supported by ruby Time.strftime. Defaults to ISO 8601 format. Example value: "2007-11-19T08:37:48-06:00".
Digit Sequence
formatstringA string of characters, digits, and symbols
Dummy Image URL
minHeightintegerthe minimum height in pixels
maxHeightintegerthe maximum height in pixels
minWidthintegerthe minimum width in pixels
maxWidthintegerthe maximum width in pixels
formatstringThe image format

Must be of the following:
  • random
  • png
  • gif
  • jpg
Exponential Distribution
lambdadecimal1The rate parameter
Formula
valuestring

Formulas allow you to use Ruby code to generate data based on custom logic. For example:

times_reached_base / at_bats + slugging

Operators

+ - * / %

Logic

< > <= >= == != and or

Conditional Statements

if my_num % 2 == 0 then 'even' else 'odd' end

if score > 10 then "high" elsif score > 5 then "medium" else "low" end

Functions

base64(str) => encodes a string as base64

code("CURRENT_TIMESTAMP") => returns a value that is will not be wrapped in quotes in the downloaded file. Use this to inject code into your data.

concat(first_name, " ", last_name) => concatenates all arguments into a single string.

date('7/4/2015') => July 4, 2015

date_diff('days', my_date, date('2015-01-01')) => The numbers of days between my_date and Jan 1, 2015. 'days', 'hours', 'minutes', and 'seconds' are also supported.

day(my_date_field) => The day of my_date_field as an integer. Optionally specify true as a second argument to return the day as string in 2 digit format.

digest(str, 'MD5|HMAC|RMD160|SHA1|SHA256|SHA384|SHA512', 'hex|base64') => digest of str with specific algorithm and encoding

epoch(datetime) => Converts a datetime field to an epoch.

field("My Field Name") => gets the value of a field. Use this to access fields that start with an uppercase letter or contain non-alphanumeric characters.

from_dataset("dataset", "column", join_criteria) => Fetches a value from a dataset.
For example, from_dataset("People", "name", id: person_id) returns the value of the "name" column from the "People" dataset where the id column matches the person_id column in the current schema.

hex(str) => encodes a string as hex

lower("XYZ") => xyz

mongo_object_id(my_id) => Output the value of my_id in MongoDB ObjectId JSON format

month(my_date_field) => The month of my_date_field as an integer. Optionally specify true as a second argument to return the month as a string in 2 digit format.

my_date + years(2) => the date 2 years after my_date. months, days, hours, minutes, and seconds are also available.

naughty(my_field, 10) => returns a naughty string 10% of the time and the value of my_field 90% of the time. Use with hidden fields (name starting with "__") to turn nice fields into naughty fields!

now() => The current date and time.

pad(field, length, fill_string, "left|right|center") => pads a string to a fixed length with filler.

format(number_value, decimals) => formats a number as a string with a fixed number of decimal places. For example: format(1.2, 3) => "1.200"

random(min, max) => generates a random number between min and max.

round(x / y, 2) => rounds to 2 decimal places

time(my_datetime_field => Returns only the time part of a datetime field.

upper("xyz") => XYZ

year(my_date_field) => The year of my_date_field as an integer

Accessing Request Parameters when Used in a Mock API

request_params['name_of_parameter'] => returns the value of a URL or query string parameter specified in the request

Handling Blanks

my_num + 1 if my_num => returns my_num + 1, or blank if my_num is blank

a + b if a and b => returns a + b, or blank if either is blank

(my_num || 0) + 1 => returns my_num + 1, or 1 if my_num is blank

if my_field.nil? then 'blank' else 'not blank' end => "blank" when my_field is blank, otherwise "not blank"

Accessing Nested JSON Objects

When a formula field is inside of a JSON array it has access to all fields in that array as well as all fields on parent objects. Both fields in the array and parent fields are accessed without a qualifier. For example, if a formula is in an array named "myArray" that has nested field named "myArray.myField", the formula can access that field as "myField" NOT "myArray.myField". When formulas need to access fields in nested objects (not in an array), however, the fully qualified field name must be used.

Geometric Distribution
probabilitydecimal0.5The probability of success
JSON Array
minItemsinteger1The minimum number of items to generate (0 to 100). Help with JSON Arrays...
maxItemsinteger5The maximum number of items to generate (0 to 100)
Money
mininteger0The minimum value
maxinteger10The maximum value
symbolstring$The currency symbol

Must be of the following:
  • $
  • £
  • ¥
  • random
  • none
My List (deprecated)
liststringThe name of a saved list
selectionStylestringrandom"random" or "sequential"
Normal Distribution
meandecimal0The mean value for the normal distribution
sddecimal1The standard deviation for the normal distribution
decimalsinteger2The number of decimals places for each generated value
Number
mininteger1The minimum value
maxinteger100The maximum value
decimalsinteger2The number of decimals
Paragraphs
mininteger1The minimum number of paragraphs
maxinteger3The maximum number of paragraphs
Phone
formatstring#-(###)###-####The phone number format

Must be of the following:
  • ###-###-####
  • (###) ###-####
  • ### ### ####
  • +# ### ### ####
  • +# (###) ###-####
  • +#-###-###-####
  • #-(###)###-####
  • ##########
Poisson Distribution
meaninteger50The mean value for the poisson distribution
Regular Expression
valuestring

The following character classes are supported:

\dnumbers
\wwords from lorem ipsum
[:alpha:]letters
[:upper:]uppercase letters
[:lower:]lowercase letters
[:name:]random first and last name
[:first_name:]random first name
[:last_name:]random last name
[:plus:]+
[:question:]?
{{my_field}}Value of field named "my field"

Examples

Aa{3}h{3,15}! => "Aaaahhhhh!"
\d{4} => "5168"
[:upper:]{2}-\d{3}-[:lower:]{1} => "XS-455-c"
((A|B|C){2})((1|2|3){3}) => "CB211"
[:plus:]\d{2} \d{3} \d{3} \d{4} => "+01 410 555 3934"
Repeating Element
minElementsinteger1The minimum number of elements to generate (0 to 100). Help with Repeated Elements...
maxElementsinteger5The maximum number of elements to generate (0 to 100)
Scenario
scenariostringThe name of a scenario
Sentences
mininteger1The minimum number of sentences
maxinteger10The maximum number of sentences
Sequence
startinteger1The first number in the sequence
stepinteger1The number to add to each subsequent value
repeatinteger1The number of times each value should occur before the step amount is added.
SQL Expression
valuestringSQL code to include verbatim in the generated output
State
onlyUSPlacesbooleanfalseTrue to restrict locations to the United States
State (abbrev)
onlyUSPlacesbooleanfalseTrue to restrict locations to the United States
Template
valuestring

Templates allow you to incorporate values from other fields by surrounding field names with {braces}.

For example, let's say you have a "first_name" field and a "last_name" field. The following template will generate a formatted name where last name comes first:

{last_name}, {first_name}

Time
minstring12:00 AMThe minimum time in HH:MM AM/PM format.
maxstring11:59 PMThe maximum time in HH:MM AM/PM format.
formatstring%T(optional) The format to output. This can be any format directive supported by ruby Time.strftime. Defaults to ISO 8601 format. Example value: "08:37:48".
URL
includeProtocolbooleantrueTrue to include a protocol in the url
includeHostbooleantrueTrue to include a hostname in the url
includePathbooleantrueTrue to include a path in the url
includeQueryStringbooleantrueTrue to include a query string in the url
Words
mininteger10The minimum number of words
maxinteger20The maximum number of words

Client Libraries

There are several client libraries for the Mockaroo API:

Example: jQuery (jsonp)

var fields = [{
    name: "yearsEmployed",
    type: "Number",
    min: 1,
    max: 30,
    decimals: 0
}, {
    name: "department",
    type: "Custom List",
    values: ["R+D", "Marketing", "HR"]
}, {
    name: "dob",
    type: "Date",
    min: "1/1/1950",
    max: "1/1/2000",
    format: "%m/%d/%Y"
}];

var url = 'https://api.mockaroo.com/api/generate.json?key=abcd1234' +
  '&fields=' + encodeURIComponent(JSON.stringify(fields));

$.ajax(url, {
    dataType: 'jsonp',
    contentType: 'application/json',
    success: function(data) {
        console.log('yearsEmployed', data.yearsEmployed);
        console.log('department', data.department);
        console.log('dob', data.dob);
    }
});

Here's a jsFiddle you can play with.

Example: Node.js

This example uses the official npm module for Mockaroo.

var Mockaroo = require('mockaroo'); // npm install mockaroo

var client = new Mockaroo.Client({
    apiKey: // your api key here
})

client.generate({
    count: 10,
    fields: [{
        name: 'id',
        type: 'Row Number'
    }, {
        name: 'transactionType',
        type: 'Custom List',
        values: ['credit', 'debit']
    }]
}).then(function(records) {
    for (var i=0; i<records.length; i++) {
        var record = records[i];
        console.log('record ' + i, 'id:' + record.id + ', transactionType:' + record.transactionType);
    }
});

Example: Java

package com.mockaroo.api.example;

import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class Client {
	public static void main(String[] args) throws IOException {
		URL url = new URL("https://api.mockaroo.com/api/generate.json?key=abcd1234");
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setDoOutput(true);
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type", "application/json");

		JSONObject yearsEmployed = new JSONObject();
		yearsEmployed.put("name", "yearsEmployed");
		yearsEmployed.put("type", "Number");
		yearsEmployed.put("min", 1);
		yearsEmployed.put("max", 30);
		yearsEmployed.put("decimals", 0);

		JSONObject department = new JSONObject();
		department.put("name", "department");
		department.put("type", "Custom List");
		JSONArray values = new JSONArray();
		values.put("R+D");
		values.put("Marketing");
		values.put("HR");
		department.put("values", values);

		JSONObject dob = new JSONObject();
		dob.put("name", "dob");
		dob.put("type", "Date");
		dob.put("min", "1/1/1950");
		dob.put("max", "1/1/2000");
		dob.put("format", "%m/%d/%Y");

		JSONArray fields = new JSONArray();
		fields.put(yearsEmployed);
		fields.put(department);
		fields.put(dob);

		OutputStream os = conn.getOutputStream();
		os.write(fields.toString().getBytes());
		os.flush();

		JSONObject data = new JSONObject(IOUtils.toString(conn.getInputStream()));

		System.out.println(data.getInt("yearsEmployed"));
		System.out.println(data.getString("department"));
		System.out.println(data.getString("dob"));
	}
}