JSON Server Example
This JSON server example is part of an article series that was rewritten in mid 2017 with up-to-date information and fresh examples.
The JSON Server is a popular tool for front-end developers for quickly setting up a fully fake REST API in less than a minute. You need to first install it via npm:
npm install -global json-server
Next, save some data in a JSON file and name it db.json:
{
"clients": [
{
"id": "59761c23b30d971669fb42ff",
"isActive": true,
"age": 36,
"name": "Dunlap Hubbard",
"gender": "male",
"company": "CEDWARD",
"email": "dunlaphubbard@cedward.com",
"phone": "+1 (890) 543-2508",
"address": "169 Rutledge Street, Konterra, Northern Mariana Islands, 8551"
},
{
"id": "59761c233d8d0f92a6b0570d",
"isActive": true,
"age": 24,
"name": "Kirsten Sellers",
"gender": "female",
"company": "EMERGENT",
"email": "kirstensellers@emergent.com",
"phone": "+1 (831) 564-2190",
"address": "886 Gallatin Place, Fannett, Arkansas, 4656"
},
{
"id": "59761c23fcb6254b1a06dad5",
"isActive": true,
"age": 30,
"name": "Acosta Robbins",
"gender": "male",
"company": "ORGANICA",
"email": "acostarobbins@organica.com",
"phone": "+1 (882) 441-3367",
"address": "697 Linden Boulevard, Sattley, Idaho, 1035"
}
]
}
Finally, start the server with the following command:
json-server --watch src/db.json
You can now access the simple REST API with a suitable client. For now, a modern browser like Chrome, Firefox or Safari will do. Open http://localhost:3000/clients and you will see your entire miniature database in JSON format. You can view items by id by using the request format http://localhost:3000/clients/{id}
. For example, opening http://localhost:3000/clients/59761c233d8d0f92a6b0570d will yield:
{
"id": "59761c233d8d0f92a6b0570d",
"isActive": true,
"age": 24,
"name": "Kirsten Sellers",
"gender": "female",
"company": "EMERGENT",
"email": "kirstensellers@emergent.com",
"phone": "+1 (831) 564-2190",
"address": "886 Gallatin Place, Fannett, Arkansas, 4656"
}
To learn more about the JSON server, check out the tutorial Mock REST APIs Using json-server
Also: See more JSON examples.
Here are the other examples in this series: