API Endpoints
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.
Usage Limits
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 |
Generate API
The Mockaroo Generate API has the following methods:
GET /api/types
Returns an array of the available types. Each object has the following keys:
GET https://api.mockaroo.com/api/types?key=(your API key)
- name (string) - The name of the type
- parameters (Object[]) - Additional options that can be specified. Each object has the following keys:
- 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.
POST https://api.mockaroo.com/api/datasets/:name?key=(your API key)&filename=(file name)
- 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 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.
POST https://api.mockaroo.com/api/datasets?key=(your API key)&name=(dataset name)&filename=(file 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.
POST https://api.mockaroo.com/api/generate(.format)?key=(your API key)
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 |
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. |
bom | boolean (optional, only used when format is csv, txt, or custom) | Set to true to include the BOM (byte order mark). Defaults to false. |
background | boolean (optional) | When set to true data will be generated in the background rather than being returned directly. The maximum amount of records that can be generated is based on your plan. A paid plan is required to use background=true. When false, the data is returned in the response body and there is a 5000 record limit regardless of plan. |
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. |
delimiter | character (optional, only used when format is custom) | The character to use as a column separator |
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. |
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. |
line_ending | string (optional, only used when format is custom) | "unix" or "windows" |
quote_char | character (optional, only used when format is custom) | The character to use when enclosing values. Defaults to double-quote. |
record_element | string (optional, only used when format is xml) | The name to give to each element representing a record |
root_element | string (optional, only used when format is xml) | The name to give to the root element in the document |
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. |
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 | The name of one of Mockaroo's types (see below) |
Response Body
If the background parameter is set to "true", the following will be returned:
{
"downloadId": number // The id of the background job. Pass this to /api/downloads/:id to get the status of the job and access the generated data when finished.
}
Otherwise, the response body will contain the generated data in the format specified by the "format" parameter you provided.
Types
The following values can be used for the type parameter:
GET /api/downloads/:id
Gets the status of a dataset generated in the background using /api/generate.
URL Parameters
- id - The download_id from /api/generate.
Response Body
{
"status": string, // "success", "failed", "queued", or "in_progress"
"error": string, // the error message if the status is failed
"recordsGenerated": number, // the number of records generated so far
"percentComplete": number, // the percentage of total records generated so far
"url": string // the URL from which the generated data can be downloaded
}
DELETE /api/downloads/:id
Deletes a download from Mockaroo. If the download is in progress it will be canceled and deleted.
- If successful, an empty 200 OK response will be returned
- If there is an error, it will be returned as JSON:
{
"error": string // The error message
}
Client Libraries
There are several client libraries for the Mockaroo API:
Node.js
- mockaroo-node (officially supported)
C#
Examples
Node.js (small files)
Here's how you can generate small datasets (up to 5000 records) using the API. This example uses the official npm module for Mockaroo.
import Mockaroo from 'mockaroo' // npm install mockaroo
const client = new Mockaroo.Client({
apiKey: process.env.MOCKAROO_API_KEY, // your API key
})
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
)
}
})
Node.js (large files)
Here's how you can use the ?background=true parameter to generate more than 5000 records at a time using the API.
import got from 'got'
import { promisify } from 'node:util'
import stream from 'node:stream'
import fs from 'node:fs'
const urlBase = `https://api.mockaroo.com`
const apiKey = process.env.MOCKAROO_API_KEY
const schema = 'My Schema'
const count = 10000
const dest = 'data.csv'
async function main() {
try {
// Start generating data in the background
const { downloadId } = await start(schema, count)
// Poll until it's done.
const { url } = await poll(downloadId)
// Download the generated file
await download(url, dest)
} catch (e) {
console.log(`Failed: ${e.message}`)
}
process.exit(0)
}
/**
* Starts data generation in the background.
*/
async function start(schema, count) {
const url =
`${urlBase}/api/generate.csv?background=true` +
`&schema=${encodeURIComponent(schema)}` +
`&count=${count}`
return await fetchAuthenticated(url)
}
/**
* Makes an authenticated fetch by passing your Mockaroo API key via the X-Api-Key header.
*/
function fetchAuthenticated(url, { headers, ...options } = { headers: {} }) {
return got(url, {
...options,
headers: {
...headers,
'X-Api-Key': apiKey,
},
}).json()
}
/**
* Polls every second to determine when data generation has completed.
* @param {number} id The download id
* @returns {Object} The API response body when data generation is completed.
*/
async function poll(id) {
return new Promise((resolve, reject) => {
setInterval(async () => {
const url = `${urlBase}/api/downloads/${id}`
const result = await fetchAuthenticated(url)
if (result.status === 'success') {
resolve(result)
} else if (result.status === 'failed') {
reject(new Error(result.error))
} else if (result.status === 'queued') {
console.log(
`queued behind ${result.position} other${
result.position === 1 ? '' : 's'
}...`
)
} else {
console.log(
`${result.recordsGenerated} (${result.percentComplete}%)...`
)
}
}, 1000)
})
}
/**
* Downloads the specified url to the dest file path
* @param {*} url The URL to download
* @param {*} file The file path to write it to
*/
async function download(url, dest) {
console.log(`downloading to ${dest}...`)
const pipeline = promisify(stream.pipeline)
await pipeline(got.stream(url), fs.createWriteStream(dest))
}
main()
jQuery (jsonp)
const 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',
},
]
const key = process.env.MOCKAROO_API_KEY // Your mockaroo API key
const url = `https://api.mockaroo.com/api/generate.json?key=${key}&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.
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"));
}
}