Documentation

Introduction

JsonServer.io is a Json Fake API Server as a Service and a powerful tool for creating faked backend APIs with ease. The main feature of this platform is a API endpoint which provides individual fake data generation. This documentation will help you to understand how jsonserver.io is working and how build a fake backend API for requesting mock data.

The Platform

JsonServer.io is not just an API, it is also a platform where you can create and manage your servers, saved resources and your teams. The platform can be found at https://app.jsonserver.io. However, this possibilities are optional except the creation of at least one fake API server to get a API token. The use of our platform requires an account which you can create here. A jsonserver.io account is completely free as long as you not subscribe for a paid plan.

The API Endpoint

Mainly it is all about to request your fake data via the API endpoint provided by jsonserver.io. The API endpoint which you have to use for your fake data requests is https://api.jsonserver.io. It is secured by a API token which is generated for each of your created API servers individually and also by https protocol, but which is not required. Due to the support of CORS (cross-origin resource sharing) on our API, you can use it from everywhere.

Request

There are two different ways to request your fake data over the API endpoint:
  • Request with schema as post body for fake data generation on demand.
  • Request your saved resources which you have created and defined via the platform UI.
This two different requests methods differ also from how to request but both requires the API token send as header parameter named X-Jsio-Token.
API Token
The use of our fake API requires always a valid API token. The token will be created together with a fake API server at our platform. After you have created at least one server, you can display the API token for this server by clicking on "Display API Token" button at the server overview page (https://api.jsonserver.io/servers).

The API token must be send with each request as header parameter named X-Jsio-Token.
POST https://api.jsonserver.io HTTP/2.0
Content-Type: application/json
X-Jsio-Token: your-api-token-here
{....}
Request with schema as post body
This request method is usually the basic one, that returns a fake data response based on the schema sent as Json defined schema in post body of the request. This request method supports only the http POST method and should always target the root url, in other words, this method will not work with a url path, if you want to work with url paths, then skip to Request saved resources.

The API endpoint expects a post body which contains a Json formatted content. This content represents the schema which is used to generate the fake data for response. A very basic request looks like this one.
POST https://api.jsonserver.io HTTP/2.0
Content-Type: application/json
X-Jsio-Token: your-api-token-here
{
    "name": "person.firstName"
}

The request above will return the following json formatted response body:
{
    "name": "John Doe"
}

The schema, which contains the definition of the returned fake data, can also contain further information like the response options, custom headers or status code. This parts of schema are prefixed with a "@" and must be defined at the root level of the schema. Lets combine the schema which is defined above and add some additional response options and headers:
{
    "@options": {
        "statusCode": 500,
        "delay": 1000
    },
    "@headers": {
        "X-Custom-Header": "Test-123"
    },
    "name": "person.firstName"
}

The response body of a request with this schema would be the same as the first one but with a status code 500, a minimum delay of 1 second and a custom header. If you can wait for it and want to know how to use spawning a number of properties or objects, then click here.
Example requests in different languages:
curl -X POST \
  -H "Content-Type: application/json" \
  -H "X-Jsio-Token: your-token-here" \
  -d '{"name": "person.firstName"}' \
  https://api.jsonserver.io
const response = await fetch('https://api.jsonserver.io', {
  method: 'POST',
  mode: 'cors',
  headers: {
    'Content-Type': 'application/json',
    'X-Jsio-Token': 'your-api-token-here'
  },
  body: JSON.stringify({
    "name": "person.firstName"
  })
});

const data = response.json();
import axios from 'axios';

// Set api token for all your requests
axios.defaults.headers.common['X-Jsio-Token'] = 'your-api-token-here';

axios.post('https://api.jsonserver.io', {"name": "person.firstName"}).then(res => {
  const fakeData = res.data;
});
use GuzzleHttp\Client;

$client = new Client([
    'base_uri' => 'https://api.jsonserver.io',
    'headers' => [
      'X-Jsio-Token' => 'your-api-token-here'
    ],
]);

$response = $client->request('POST', '/', [
  'json' => [
    'name' => 'person.firstName'
  ]
]);
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("https://api.jsonserver.io");

String json = "{\"name\": \"person.firstName\"}";
StringEntity entity = new StringEntity(json);
httpPost.setEntity(entity);
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("X-Jsio-Token", "your-api-token-here");

CloseableHttpResponse response = client.execute(httpPost);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
package main

import (
	"net/http"
	"io/ioutil"
)

func main() {
	url := "https://api.jsonserver.io"

  var jsonStr = []byte(`{"name":"person.firstName"}`)
  req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
  req.Header.Set("X-Jsio-Token", "your-api-token-here")
  req.Header.Set("Content-Type", "application/json")

  client := &http.Client{}
  resp, err := client.Do(req)

  defer resp.Body.Close()

  fmt.Println("response Status:", resp.Status)
  fmt.Println("response Headers:", resp.Header)
  body, _ := ioutil.ReadAll(resp.Body)
  fmt.Println("response Body:", string(body))
}
import requests

headers = {'Content-type': 'application/json', 'X-Jsio-Token': 'your-api-token-here'}
fake_schema = {'name': 'person.fistName'}
response = requests.post('https://api.jsonserver.io', fake_schema, headers)

json_response = response.json()
fakeData = json_response['data']
Request saved resources
This request method requires at least one saved resource, which can be created via the platform. A saved resource is nothing else then a schema which is stored by your fake API server at our platform with optional response options and headers. All you have to do is open your fake API server at https://app.jsonserver.io/servers and create a new resource by click the plus button on the left.

When creating a new resource you have to give it an url path (route) that is relevant for the request. The API endpoint for requesting saved resources allows GET, POST, PATCH, PUT and DELETE as http method.

Let's say you have created a saved resource with the url path /shelves/*/books. The request to receive the fake data as defined in your saved resource would looks like this one:
GET https://api.jsonserver.io/shelves/1234/books/5678 HTTP/2.0
Content-Type: application/json
X-Jsio-Token: your-api-token-here
The response of the request defined above will be based on the saved resources schema and maybe contains custom headers and status code.
Example requests in different languages:
curl -X GET \
  -H "X-Jsio-Token: your-token-here" \
  https://api.jsonserver.io/shelves/123/books/567
const url = 'https://api.jsonserver.io/shelves/123/books/567';
const response = await fetch(url, {
  method: 'GET',
  mode: 'cors',
  headers: {
    'X-Jsio-Token': 'your-api-token-here'
  }
});

const data = response.json();
import axios from 'axios';

// Set api token for all your requests
axios.defaults.headers.common['X-Jsio-Token'] = 'your-api-token-here';

axios.get('https://api.jsonserver.io/shelves/123/books/567').then(res => {
  const fakeData = res.data;
});
use GuzzleHttp\Client;

$client = new Client([
    'base_uri' => 'https://api.jsonserver.io',
    'headers' => [
      'X-Jsio-Token' => 'your-api-token-here'
    ],
]);

$response = $client->request('GET', '/shelves/123/books/567');
CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("https://api.jsonserver.io/shelves/123/books/567");
httpGet.setHeader("X-Jsio-Token", "your-api-token-here");
CloseableHttpResponse response = client.execute(httpGet);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
package main

import (
	"net/http"
	"io/ioutil"
)

func main() {
	url := "https://api.jsonserver.io/shelves/123/books/567"

  req, err := http.NewRequest("GET", url)
  req.Header.Set("X-Jsio-Token", "your-api-token-here")

  client := &http.Client{}
  resp, err := client.Do(req)

  defer resp.Body.Close()

  fmt.Println("response Status:", resp.Status)
  fmt.Println("response Headers:", resp.Header)
  body, _ := ioutil.ReadAll(resp.Body)
  fmt.Println("response Body:", string(body))
}
import requests

url = 'https://api.jsonserver.io/shelves/123/books/567'
headers = {'X-Jsio-Token': 'your-api-token-here'}
response = requests.get(url, headers)

json_response = response.json()
fakeData = json_response['data']

Response

The response of a successfully fake data request contains at least the following response headers:
access-control-allow-credentials: true
access-control-allow-headers: *
access-control-allow-methods: GET, POST, PATCH, PUT, DELETE
access-control-allow-origin: *
content-type: application/json; charset=utf-8
etag: xxxxxxxxxxxxxxxxxxxxxxxxx
status: XXX

In this case the response body is a json formatted string contains the fake data as defined in post body or in the saved resource via our platform UI. But there also some cases the response body and headers are differs from the succeeded fake data requests e.g. exceeded request limit or a bad request / invalid request etc. Lets take a look at the responses of these cases.
Unauthorized Request (401)
If you try to request one of your server with a wrong or invalid API token, you will get a 401 response with the following response body: Example response:
{
    "error": {
        "status": 401,
        "reason": "Unauthorized",
        "message": "...",
        "details": []
    }
}
Invalid Request (400)
In case of a invalid schema which has been sent in post body for requesting fake data generation, the API endpoint will return the following response body. Example response:
{
    "error": {
        "status": 400,
        "reason": "Invalid",
        "message": "...",
        "details": {
            "hint": "..."
        }
    }
}
Limit Reached (429)
If you hit the request limit, the API endpoint will response an error body with status code 429. Due to our request quota recharge feature, you will gain as many new requests as your plan defines per minute, so you will be able to have some free request quota again after some waiting time. Example response:
{
  "error": {
    "status": 429,
    "reason": "LimitReached",
    "message": "...",
    "details": []
  }
}
Resource not found (404)
If you try to request a saved resource which does not exists, you will get the following response: Example response:
{
    "error": {
        "status": 404,
        "reason": "NotFound",
        "message": "...",
        "details": {
            "info": "...",
            "hint": "..."
        }
    }
}

Fake Schema

The fake schema defines the response fake data structure and generated content. We provide a wide range of fake possibilities for generating data and these are also constantly extended. However, there is another very useful function besides the faking of single fields / properties we want to start first with: The spawning of arrays.

Array Spawning

The spawning of structures or values as array can be achieved by a special syntax in the schema, which is a keyword named spawn that expect a int value as parameter within the round brackets right behind the keyword e.g. spawn(10). The are two possibilities of spawning arrays: Spawning an array by structure and spawning by a simple value. This two possibilities are intended to achieve different results in spawning. There is also a detail at spawning of root level structures which should be considered, which is described in the next sections.

Spawning Array by Structure
The structure is represented by a simple json object with fake expressions which can also contain further nested objects and arrays. There is also a different between spawning of root level structures and nested structures. The spawning of a root level structure does expect only the spawn keyword as property name whereas the spawning of a non root level structure expects a property name combined with the keyword.

The spawning of a root level structure:
{
  "spawn(3)": {
    "id": "crypt.uuid",
    "email": "user.email"
  }
}
Response body:
[
  {
    "id": "fd9e1067-2b13-4539-895e-eaa87afb9558",
    "name": "Catherine"
  },
    "id": "ca9e542b-7d84-4726-9e61-31baa1d25ba2",
    "name": "Cortney"
  },
    "id": "4bf3309b-b72c-4b48-a1fd-3bcdbd574443",
    "name": "Loriann"
  }
]

The spawning of a non root level structure:
{
  "id":"crypt.uuid",
  "customer": "company.name",
  "orders|spawn(3)": {
    "id": "crypt.uuid",
    "product": "product.name",
    "amount": "number.int(300, 500)"
  }
}
Response body:
{
  "id": "16812b67-80a9-4d26-b122-b67f7ff558ea",
  "customer": "Kameeron Industries",
  "orders": [
    {
      "id": "ef772c25-9709-470e-96e1-c95f6966b8f7",
      "product": "Freshdox",
      "amount": 373
    },
    {
      "id": "c9177926-330c-4fd8-9a7c-c288f86870f0",
      "product": "Tam Rantrax",
      "amount": 399
    },
    {
      "id": "8730562a-db1e-4e64-8bed-738aac256881",
      "product": "Ontolight",
      "amount": 373
    }
  ]
}

Spawning Array by Value
The value is represented by a simple string or numeric value. The result of spawning a value is an simple array with fake values and numeric keys. The spawning of a non root level structure:
{
  "id":"crypt.uuid",
  "names": "person.firstName|spawn(3)"
}
Response body:
{
  "id": "dcb757c1-17fb-4524-a3d4-4bfb022e6614",
  "names": [
    "Leisa",
    "Lasonya",
    "Serafina"
  ]
}

Subjects

A subject or so-called expressions defines the type and kind of the data which has to be generated. If you want for instance generate a insurance number then you can use person.insuranceNumber to generate a random insurance number.
{
  "name": {
    "first": "person.firstName",
    "middle": "person.firstName",
    "last": "person.lastName",
  },
  "insurance": {
    "number": "person.insuranceNumber"
  },
  "age": "person.age"
}
Some subjects provides the possibility to influence the generated result by using parameters right behind the subject. The following schema example will generate a age between 20 and 30.
{
  "age": "person.age(20, 30)"
}
List of Subjects
person
Expression Parameter Description
person.firstName
A random first name.
person.lastName
A random last name.
person.fullName
A random full name.
person.age
min (default: 1) optional
max (default: 100) optional
A random age.
person.weightKG
min (default: 40) optional
max (default: 150) optional
A random weight number for KG.
person.weightLBS
min (default: 80) optional
max (default: 300) optional
A random weight for LBS
person.bodyHeightCm
min (default: 150) optional
max (default: 200) optional
A random body high in cm.
person.bodyHeightInch
min (default: 60) optional
max (default: 80) optional
A random body height in inch.
person.maritalStatus
A random material status.
person.hobbies
min (default: 1) optional
max (default: 5) optional
A random hobby.
person.insuranceNumber
A random insurance number.
person.gender
A random gender.
person.language
A random language.
person.languages
min (default: 2) optional
max (default: 4) optional
One or more random languages as array.
person.title
A random title (Mr. Ms. Master etc.)
person.degree
A random degree.
person.origin
A random origin (country).
person.academicTitle
A random academic Title.
person.academicRank
A random academic rank name.
person.militaryTitle
A random military title.
address
Expression Parameter Description
address.country
A random name of a country.
address.state
countryCode (default: *) optional
A random state name of the US country or country passed by country code parameter.
The result is a US state by default, use the country code parameter to choose a different country.Currently available country codes are: US
address.stateCode
countryCode (default: *) optional
A random state code of the US country or country passed by country code parameter.
The result is a US state code by default, use the country code parameter to choose a different country.Currently available country codes are: US*
address.countryCode
A random country code from the world.
address.zipCode
A random 5-digits zip code.
address.postalCode
A random 5-digits postal code.
address.zipCodeLong
A random long zip code #####-####.
address.streetSupplement
A random street supplement (e.g. house number, apartment number etc.)
address.street
countryCode (default: *) optional
A random name of a street with a appended street supplement.
The result is a street from US country by default, use the country code parameter to choose a different country.Currently available country codes are: US*
address.streetName
c (default: *) optional
A random name of a street.
The result is a street name from US country by default, use the country code parameter to choose a different country.Currently available country codes are: US*
address.city
c (default: *) optional
A random name of a city of the world.
The result is a world city name by default, use the country code parameter to choose a country.Currently available country codes are: US, DE
address.latitude
A random latitude as float value.
address.longitude
A random longitude as float value.
address.coordinates
A random array contains a latitude and a longitude with keys named same.
crypt
Expression Parameter Description
crypt.uuid
A random UUID string.
crypt.md2
A random md2 hash.
crypt.md4
A random md4 hash.
crypt.md5
A random md5 hash.
crypt.sha1
A random sh1 hash.
crypt.sha256
A random sha256 hash.
crypt.sha384
A random sha384 hash.
crypt.sha512
A random sha512 hash.
crypt.ripemd128
A random ripemd128 hash.
crypt.ripemd160
A random ripemd160 hash.
crypt.ripemd256
A random ripemd256 hash.
crypt.ripemd320
A random ripemd320 hash.
crypt.whirlpool
A random whirlpool hash.
crypt.tiger128
A random tiger128 hash.
crypt.tiger160
A random tiger160 hash.
crypt.tiger192
A random tiger192 hash.
crypt.snefru
A random snefru hash.
crypt.gost
A random gost hash.
crypt.adler32
A random adler32 hash.
crypt.crc32
A random crc32 hash.
crypt.crc32b
A random crc32b hash.
crypt.haval128
A random haval128 hash.
crypt.haval160
A random haval160 hash.
crypt.haval192
A random haval192 hash.
crypt.haval224
A random haval224 hash.
crypt.haval256
A random haval256 hash.
crypt.base64
A random base64 string.
crypt.rsaPrivateKey512
A private rsa key.
crypt.rsaPrivateKey1024
A private rsa key.
crypt.rsaPrivateKey2048
A private rsa key.
crypt.rsaPrivateKey4096
A private rsa key.
crypt.rsaPublicKey512
A public rsa key.
crypt.rsaPublicKey1024
A public rsa key.
crypt.rsaPublicKey2048
A public rsa key.
crypt.rsaPublicKey4096
A public rsa key.
phone
Expression Parameter Description
phone.mobile
A random mobile phone number.
phone.mobileE164
phone.local
A random local phone number.
phone.domestic
A random domestic phone number.
user
Expression Parameter Description
user.username
A random username.
user.fantasyName
A random fantasy name.
user.password
A random password.
user.email
A random email address.
number
Expression Parameter Description
number.int
min (default: 0) optional
max (default: 1000) optional
A random integer.
number.float
min (default: 0) optional
max (default: 1000) optional
decimals (default: 1) optional
A random float.
number.bool
A random bool value.
internet
Expression Parameter Description
internet.ip4
A random ipv4 address.
internet.ip6
A random ipv6 address.
internet.email
A random email address.
internet.url
A random url.
internet.tld
A random top level domain.
internet.userAgent
A random user agent.
internet.browser
A random browser name.
text
Expression Parameter Description
text.sentence
count (default: 1) optional
On or more sentences.
text.paragraph
count (default: 1) optional
One or more paragraphs.
text.word
min (default: 1) optional
max (default: 1) optional
One or more random words as string.
text.words
min (default: 3) optional
max (default: 8) optional
One or more random words as array
text.businessBuzzWords
min (default: 3) optional
max (default: 6) optional
An array with random buzz words.
text.headline
A random headline.
text.hashtags
count (default: 6) optional
A array with random hashtag words.
currency
Expression Parameter Description
currency.code
A random 3 letter currency code.
currency.name
A random currency name.
currency.sign
A random currency sign.
food
Expression Parameter Description
food.name
A random food name.
food.additive
A random additive.
food.additives
min (default: 0) optional
max (default: 6) optional
One or more random additives as array.
food.nutrient
A random nutrient.
food.nutrients
min (default: 0) optional
max (default: 6) optional
One ore more nutrients as array.
food.additiveCode
A random additive code (e.g. E123)
food.additiveCodes
min (default: 0) optional
max (default: 6) optional
One or more additive codes as array.
product
Expression Parameter Description
product.name
A random product name.
product.brand
A random brand name or a product.
product.sku
A random SKU.
product.isbn
A random ISBN.
product.upc
A random UPC
product.ean
A random EAN number.
product.type
A random product type.
product.sizeCode
A random size code (s, m, xl etc.)
product.size
A random size as word (small, medium...)
product.stars
A random int from 1 to 5.
product.starsFloat
product.reviews
A random number of product reviews.
company
Expression Parameter Description
company.name
A random name of a company.
company.slogan
A random slogan of a company.
company.industry
A random industry.
company.department
A random department of a company.
company.legalType
A random company legal type.
company.position
A random slogan of a company.
company.cin
A random CIN.
company.ein
A random EIN.
employee
Expression Parameter Description
employee.skills
min (default: 3) optional
max (default: 8) optional
One ore more skills as array.
employee.ein
A random EIN.
employee.job
A random job name.
employee.salary
A random integer for salary.
employee.intensity
A random job intensity name (part-time, full-time)
custom
Expression Parameter Description
custom.random
values optional
A random value from the values given by parameters.
custom.value
value
A custom value from first parameter.
custom.format
format optional
A custom format given by the first parameter.
Use the following placeholder to generate random characters.%a for a-z, %A for A-Z, # for 0-9, any other char will be keep as is.
color
Expression Parameter Description
color.name
A random color name.
color.hex
A random color hex value (e.g. #FFFFFF).
color.hexValue
A random hex value (e.g. FFFFFF).
date
Expression Parameter Description
date.format
format optional
A random formatted date, use first parameter for format.
date.unixTimestamp
A random unix timestamp.
date.timestamp
A random timestamp (0000-00-00 00:00:00)
date.date
A random date (0000-00-00).
date.time
A random time (00:00:00)
bank
Expression Parameter Description
bank.name
A random name of a bank.
bank.creditCardBrand
A random credit card brand name.
bank.creditCardNumber
A random credit card number.
bank.creditCardLast4
A random 4-digit number represents the last 4 of a credit card number.
bank.creditCardCVC
A random CVC number used by credit cards.
bank.iban
A random IBAN formatted string.
bank.bic
A random BIC formatted string.