Mockaroo APIs
Overview
Mockaroo offers two different approaches for downloading data programmatically:
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 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:
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.
Plan | Limit |
---|---|
Free | 200 requests/day |
Silver | 1,000,000 records/day |
Gold | 10,000,000 records/day |
Data API
The Mockaroo Data API has the following methods:
GET /api/types
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
POST /api/datasets/:name
Uploads a dataset. Specify the data in the request body and the mime type as the Content-Type header.Content-Type must be text/csv or text/plain.
- name (required) The name of the dataset to create or update.
- filename (optional) The name of the original file. The file name must have a .csv or .txt extension.
- project (optional) The name of an existing project to add the dataset to.
Example (JavaScript)
const fetch = require('node-fetch') const fs = require('fs') function upload(apiKey, name, path) { fetch(`https://api.mockaroo.com/api/datasets/${encodeURIComponent(name)}?key=${encodeURIComponent(apiKey)}`, { method: 'post', body: fs.readFileSync(path), headers: { "content-type": "text/csv" } }) .then(res => res.json()) .then(result => console.log(result)) }
DELETE /api/datasets/:name
Deletes a dataset by name.
- name (required) The name of the dataset to delete.
Example (JavaScript)
const fetch = require('node-fetch') const fs = require('fs') function destroy(apiKey, name, path) { fetch(`https://api.mockaroo.com/api/datasets/${encodeURIComponent(name)}?key=${encodeURIComponent(apiKey)}`, { method: 'delete' }) .then(res => res.json()) .then(result => console.log(result)) }
POST /api/generate(.format)
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:
Format | URL | Description |
---|---|---|
json | https://api.mockaroo.com/api/generate.json | Results are returned as a json object. Results will be returned as an array if the "size" query string parameter is greater than 1. |
csv | https://api.mockaroo.com/api/generate.csv | Comma separated values. The first row will contain the field names. Subsequent rows will contain the generated data values. |
txt | https://api.mockaroo.com/api/generate.txt | Tab-separated values. The first row will contain the field names. Subsequent rows will contain the generated data values. |
custom | https://api.mockaroo.com/api/generate.custom | Specify 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. |
sql | https://api.mockaroo.com/api/generate.sql | Results are returned as SQL insert statements. |
xml | https://api.mockaroo.com/api/generate.xml | Results are returned as an xml document. |
Query String Parameters
Parameter | Type | Description |
---|---|---|
key | string | (required) Your api key |
callback | string | (optional) The name of a javascript function to call in the response. If specified, the response will be in jsonp format. |
count | integer | (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. |
array | boolean | (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_nulls | boolean | (optional) When generating json data, Mockaroo will omit keys with null values if this is set to false. |
include_header | boolean | (optional) Only relevant for csv format. Set to false to omit the header row. Defaults to true. |
schema | string | (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_element | string | (optional, only used when format is xml) The name to give to the root element in the document |
record_element | string | (optional, only used when format is xml) The name to give to each element representing a record |
delimiter | character | (optional, only used when format is custom) The character to use as a column separator |
quote_char | character | (optional, only used when format is custom) The character to use when enclosing values. Defaults to double-quote. |
line_ending | string | (optional, only used when format is custom) "unix" or "windows" |
bom | boolean | (optional, only used when format is csv, txt, or custom) true to include the BOM (byte order mark). Defaults to false. |
fields | json 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:
Parameter | Type | Default | Description |
---|---|---|---|
name | string | The 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... | |
percentBlank | integer | 0 | An integer between 0 and 100 that determines what percent of the generated values will be null |
formula | string | 0 | Alters the generated value using Mockaroo formula syntax. Use this to refer to the value of this field. |
type | string | One of Mockaroo's 143 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:
Parameter | Type | Default | Description | ||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Avatar | |||||||||||||||||||||||||
height | integer | the image height in pixels | |||||||||||||||||||||||
width | integer | the image height in pixels | |||||||||||||||||||||||
Binomial | |||||||||||||||||||||||||
probability | decimal | 0.5 | The probability of success | ||||||||||||||||||||||
Character Sequence | |||||||||||||||||||||||||
format | string | A string of characters, digits, and symbols | |||||||||||||||||||||||
Country | |||||||||||||||||||||||||
countries | array | An array of countries to restrict the generated locations to | |||||||||||||||||||||||
Custom List | |||||||||||||||||||||||||
values | array | An array of values to pick from. Each value should be a string. | |||||||||||||||||||||||
selectionStyle | string | random | See list distribution types. Must be of the following:
| ||||||||||||||||||||||
Dataset Column | |||||||||||||||||||||||||
dataset | string | The name of a saved dataset | |||||||||||||||||||||||
column | string | The name of the column in the saved dataset | |||||||||||||||||||||||
selectionStyle | string | random | See list distribution types. Must be of the following:
| ||||||||||||||||||||||
Date | |||||||||||||||||||||||||
min | string | 1/16/2021 | The minimum date in mm/dd/yyyy format. | ||||||||||||||||||||||
max | string | 1/16/2020 | The maximum date in mm/dd/yyyy format. | ||||||||||||||||||||||
format | string | %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". | ||||||||||||||||||||||
Datetime | |||||||||||||||||||||||||
min | string | 1/16/2021 | The minimum date in mm/dd/yyyy format. | ||||||||||||||||||||||
max | string | 1/16/2020 | The maximum date in mm/dd/yyyy format. | ||||||||||||||||||||||
format | string | %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 | |||||||||||||||||||||||||
format | string | A string of characters, digits, and symbols | |||||||||||||||||||||||
Dummy Image URL | |||||||||||||||||||||||||
minHeight | integer | the minimum height in pixels | |||||||||||||||||||||||
maxHeight | integer | the maximum height in pixels | |||||||||||||||||||||||
minWidth | integer | the minimum width in pixels | |||||||||||||||||||||||
maxWidth | integer | the maximum width in pixels | |||||||||||||||||||||||
format | string | The image format Must be of the following:
| |||||||||||||||||||||||
Exponential Distribution | |||||||||||||||||||||||||
lambda | decimal | 1 | The rate parameter | ||||||||||||||||||||||
Formula | |||||||||||||||||||||||||
value | string | Formulas allow you to use Ruby code to generate data based on custom logic. For example:
Operators
Logic
Conditional Statements
Functions
Accessing Request Parameters when Used in a Mock API
Handling Blanks
Accessing Nested JSON ObjectsWhen 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 | |||||||||||||||||||||||||
probability | decimal | 0.5 | The probability of success | ||||||||||||||||||||||
JSON Array | |||||||||||||||||||||||||
minItems | integer | 1 | The minimum number of items to generate (0 to 100). Help with JSON Arrays... | ||||||||||||||||||||||
maxItems | integer | 5 | The maximum number of items to generate (0 to 100) | ||||||||||||||||||||||
Money | |||||||||||||||||||||||||
min | integer | 0 | The minimum value | ||||||||||||||||||||||
max | integer | 10 | The maximum value | ||||||||||||||||||||||
symbol | string | $ | The currency symbol Must be of the following:
| ||||||||||||||||||||||
My List (deprecated) | |||||||||||||||||||||||||
list | string | The name of a saved list | |||||||||||||||||||||||
selectionStyle | string | random | "random" or "sequential" | ||||||||||||||||||||||
Nato Phonetic | |||||||||||||||||||||||||
min | integer | 10 | The minimum number of words | ||||||||||||||||||||||
max | integer | 20 | The maximum number of words | ||||||||||||||||||||||
Normal Distribution | |||||||||||||||||||||||||
mean | decimal | 0 | The mean value for the normal distribution | ||||||||||||||||||||||
sd | decimal | 1 | The standard deviation for the normal distribution | ||||||||||||||||||||||
decimals | integer | 2 | The number of decimals places for each generated value | ||||||||||||||||||||||
Number | |||||||||||||||||||||||||
min | integer | 1 | The minimum value | ||||||||||||||||||||||
max | integer | 100 | The maximum value | ||||||||||||||||||||||
decimals | integer | 2 | The number of decimals | ||||||||||||||||||||||
Paragraphs | |||||||||||||||||||||||||
min | integer | 1 | The minimum number of paragraphs | ||||||||||||||||||||||
max | integer | 3 | The maximum number of paragraphs | ||||||||||||||||||||||
Phone | |||||||||||||||||||||||||
format | string | #-(###)###-#### | The phone number format Must be of the following:
| ||||||||||||||||||||||
Poisson Distribution | |||||||||||||||||||||||||
mean | integer | 50 | The mean value for the poisson distribution | ||||||||||||||||||||||
Regular Expression | |||||||||||||||||||||||||
value | string | The following character classes are supported:
ExamplesAa{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 | |||||||||||||||||||||||||
minElements | integer | 1 | The minimum number of elements to generate (0 to 100). Help with Repeated Elements... | ||||||||||||||||||||||
maxElements | integer | 5 | The maximum number of elements to generate (0 to 100) | ||||||||||||||||||||||
Scenario | |||||||||||||||||||||||||
scenario | string | The name of a scenario | |||||||||||||||||||||||
Sentences | |||||||||||||||||||||||||
min | integer | 1 | The minimum number of sentences | ||||||||||||||||||||||
max | integer | 10 | The maximum number of sentences | ||||||||||||||||||||||
Sequence | |||||||||||||||||||||||||
start | integer | 1 | The first number in the sequence | ||||||||||||||||||||||
step | integer | 1 | The number to add to each subsequent value | ||||||||||||||||||||||
repeat | integer | 1 | The number of times each value should occur before the step amount is added. | ||||||||||||||||||||||
SQL Expression | |||||||||||||||||||||||||
value | string | SQL code to include verbatim in the generated output | |||||||||||||||||||||||
State | |||||||||||||||||||||||||
onlyUSPlaces | boolean | false | True to restrict locations to the United States | ||||||||||||||||||||||
State (abbrev) | |||||||||||||||||||||||||
onlyUSPlaces | boolean | false | True to restrict locations to the United States | ||||||||||||||||||||||
Template | |||||||||||||||||||||||||
value | string | 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 | |||||||||||||||||||||||||
min | string | 12:00 AM | The minimum time in HH:MM AM/PM format. | ||||||||||||||||||||||
max | string | 11:59 PM | The maximum time in HH:MM AM/PM format. | ||||||||||||||||||||||
format | string | %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 | |||||||||||||||||||||||||
includeProtocol | boolean | true | True to include a protocol in the url | ||||||||||||||||||||||
includeHost | boolean | true | True to include a hostname in the url | ||||||||||||||||||||||
includePath | boolean | true | True to include a path in the url | ||||||||||||||||||||||
includeQueryString | boolean | true | True to include a query string in the url | ||||||||||||||||||||||
Words | |||||||||||||||||||||||||
min | integer | 10 | The minimum number of words | ||||||||||||||||||||||
max | integer | 20 | The maximum number of words |
Client Libraries
There are several client libraries for the Mockaroo API:
- Node.js
- mockaroo-node (officially supported)
- C#
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")); } }