Tutorial

JSON Server (json-server)

Published on August 4, 2022
author

Pankaj

JSON Server (json-server)

Today we will look into a very handy tool json-server, which can give you a mock rest json server in a minute. In a regular enterprise application, you work with many teams and third party APIs. Imagine you have to call a third party restful web service that will get you JSON data to work on. You are in a tight schedule, so you can’t wait for them to finish their work and then start your own. If you wish to have a mockup Rest Web service in place to get the demo data for you, then json-server is the tool you are looking for.

JSON Server

json server, json-server JSON Server is a Node Module that you can use to create demo rest json webservice in less than a minute. All you need is a JSON file for sample data.

Installing JSON Server

You should have NPM installed on your machine. If not, then refer this post to install NPM. Below shows the one liner command to install json-server with output on my machine.

$ npm install -g json-server
npm WARN deprecated graceful-fs@3.0.8: graceful-fs v3.0.0 and before will fail on node releases >= v7.0. Please update to graceful-fs@^4.0.0 as soon as possible. Use 'npm ls graceful-fs' to find it in the tree.
/usr/local/bin/json-server -> /usr/local/lib/node_modules/json-server/bin/index.js
- bytes@2.3.0 node_modules/json-server/node_modules/raw-body/node_modules/bytes
/usr/local/lib
└─┬ json-server@0.8.10
  ├─┬ body-parser@1.15.1
  │ └── bytes@2.3.0
  ├─┬ compression@1.6.1
  │ └── bytes@2.2.0
  ├─┬ lowdb@0.10.3
  │ └─┬ steno@0.4.4
  │   └── graceful-fs@4.1.4
  ├─┬ update-notifier@0.5.0
  │ └─┬ configstore@1.4.0
  │   ├── graceful-fs@4.1.4
  │   └─┬ write-file-atomic@1.1.4
  │     └── graceful-fs@4.1.4
  └─┬ yargs@4.7.0
    ├─┬ pkg-conf@1.1.2
    │ └─┬ load-json-file@1.1.0
    │   └── graceful-fs@4.1.4
    └─┬ read-pkg-up@1.0.1
      └─┬ read-pkg@1.1.0
        └─┬ path-type@1.1.0
          └── graceful-fs@4.1.4

$

Checking json-server version and options

$ json-server -v
0.8.10

$ json-server -help
/usr/local/bin/json-server [options] <source>

Options:
  --config, -c       Path to config file           [default: "json-server.json"]
  --port, -p         Set port                                    [default: 3000]
  --host, -H         Set host                               [default: "0.0.0.0"]
  --watch, -w        Watch file(s)                                     [boolean]
  --routes, -r       Path to routes file
  --static, -s       Set static files directory
  --read-only, --ro  Allow only GET requests                           [boolean]
  --no-cors, --nc    Disable Cross-Origin Resource Sharing             [boolean]
  --no-gzip, --ng    Disable GZIP Content-Encoding                     [boolean]
  --snapshots, -S    Set snapshots directory                      [default: "."]
  --delay, -d        Add delay to responses (ms)
  --id, -i           Set database id property (e.g. _id)         [default: "id"]
  --quiet, -q        Suppress log messages from output                 [boolean]
 
$

Run JSON Server

Now it’s time to start our json-server. Below is a sample file with my employees json data.

{
  "employees": [
    {
      "id": 1,
      "name": "Pankaj",
      "salary": "10000"
    },
    {
      "name": "David",
      "salary": "5000",
      "id": 2
    }
  ]
}

Important point here is the name of array i.e employees. JSON server will create the REST APIs based on this. Let’s start our json-server with above file.

$ json-server --watch db.json

  \{^_^}/ hi!

  Loading db.json
  Done

  Resources
  https://localhost:3000/employees

  Home
  https://localhost:3000

  Type s + enter at any time to create a snapshot of the database
  Watching...

Don’t close this terminal, otherwise it will kill the json-server. Below are the sample CRUD requests and responses.

JSON Server GET - Read All Employees

$ curl -X GET -H "Content-Type: application/json"  "https://localhost:3000/employees"
[
  {
    "id": 1,
    "name": "Pankaj",
    "salary": "10000"
  },
  {
    "name": "David",
    "salary": "5000",
    "id": 2
  }
]
$

Get Employee based on ID from json-server

$ curl -X GET -H "Content-Type: application/json"  "https://localhost:3000/employees/1"
{
  "id": 1,
  "name": "Pankaj",
  "salary": "10000"
}
$

JSON Server POST - Create an Employee

$ curl -X POST -H "Content-Type: application/json" -d '{"name": "Lisa","salary": "2000"}' "https://localhost:3000/employees"
{
  "name": "Lisa",
  "salary": 2000,
  "id": 3
}
$

JSON Server PUT - Update Employee Data

$ curl -XPUT -H "Content-Type: application/json" -d '{"name": "Lisa", "salary": "8000"}' "https://localhost:3000/employees/3"
{
  "name": "Lisa",
  "salary": 8000,
  "id": 3
}
$

JSON Server DELETE - Delete an Employee

$ curl -X DELETE -H "Content-Type: application/json"  "https://localhost:3000/employees/2"
{}
$ curl -GET -H "Content-Type: application/json"  "https://localhost:3000/employees"
[
  {
    "id": 1,
    "name": "Pankaj",
    "salary": "10000"
  },
  {
    "name": "Lisa",
    "salary": 8000,
    "id": 3
  }
]
$

As you can see that with a simple JSON, json-server creates demo APIs for us to use. Note that all the PUT, POST, DELETE requests are getting saved into db.json file. Now the URIs for GET and DELETE are same, similarly it’s same for POST and PUT requests. Well, we can create our custom URIs too with a simple mapping file.

json-server custom routes

Create a file with custom routes for our json-server to use. routes.json

{
  "/employees/list": "/employees",
  "/employees/get/:id": "/employees/:id",
  "/employees/create": "/employees",
  "/employees/update/:id": "/employees/:id",
  "/employees/delete/:id": "/employees/:id"
}

We can also change the json-server port and simulate like a third party API, just change the base URL when the real service is ready and you will be good to go. Now start the JSON server again as shown below.

$ json-server --port 7000 --routes routes.json --watch db.json
(node:60899) fs: re-evaluating native module sources is not supported. If you are using the graceful-fs module, please update it to a more recent version.

  \{^_^}/ hi!

  Loading db.json
  Loading routes.json
  Done

  Resources
  https://localhost:7000/employees

  Other routes
  /employees/list -> /employees
  /employees/get/:id -> /employees/:id
  /employees/create -> /employees
  /employees/update/:id -> /employees/:id
  /employees/delete/:id -> /employees/:id

  Home
  https://localhost:7000

  Type s + enter at any time to create a snapshot of the database
  Watching...

It’s showing the custom routes defined by us.

json-server example with custom routes

Below is the example of some of the commands and their output with custom routes.

$ curl -X GET -H "Content-Type: application/json"  "https://localhost:7000/employees/list"
[
  {
    "id": 1,
    "name": "Pankaj",
    "salary": "10000"
  },
  {
    "name": "Lisa",
    "salary": 8000,
    "id": 3
  }
]

$ curl -X GET -H "Content-Type: application/json"  "https://localhost:7000/employees/get/1"
{
  "id": 1,
  "name": "Pankaj",
  "salary": "10000"
}

$ curl -X POST -H "Content-Type: application/json" -d '{"name": "Lisa","salary": "2000"}' "https://localhost:7000/employees/create"
{
  "name": "Lisa",
  "salary": 2000,
  "id": 4
}

$ curl -XPUT -H "Content-Type: application/json" -d '{"name": "Lisa", "salary": "8000"}' "https://localhost:7000/emloyees/update/4"
{
  "name": "Lisa",
  "salary": 8000,
  "id": 4
}

$ curl -XDELETE -H "Content-Type: application/json"  "https://localhost:7000/employees/delete/4"
{}

$ curl -GET -H "Content-Type: application/json"  "https://localhost:7000/employees/list"
[
  {
    "id": 1,
    "name": "Pankaj",
    "salary": "10000"
  },
  {
    "name": "Lisa",
    "salary": 8000,
    "id": 3
  }
]
$

JSON server provides some other useful options such as sorting, searching and pagination. That’s all for json-server, it’s my go to tool whenever I need to create demo Rest JSON APIs. Reference: json-server GitHub

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
February 9, 2022

How do i download?

- Ezzeldin Ahmed

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    May 19, 2021

    Hi, nice but how did you get the HTTPS, after installing and running, the “resources” and “home” show only http :-( And unfortunately, my app needs secure socket. Thanx

    - Widchris

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      December 24, 2020

      Helpful tutorial

      - madfinger

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        June 5, 2020

        how to do in live server

        - hussian

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          January 2, 2020

          hi can i use primary key to save id in json-server. If yes, please share the code. Thank you.

          - Deepti Jain

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            November 26, 2019

            Is purely open source…can we use it in our production?

            - Hitesh Singh

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              March 28, 2019

              if we write get post delete directly in json server then we don’t have to write it in visual studio code in component?

              - Sonali Swami

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                September 12, 2018

                It is interesting and easy to learn. Good article. In SQl we create a database like HRM and create multiple tables like employee, login, salary etc. Could you please let me know how to create this kind of database in JSON

                - Joga Singh Rawat

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  June 20, 2018

                  Please take in account that for Windows the single quote character did not work and I ended up escaping the double quote: curl -X POST -H “Content-Type: application/json” -d “{\“id\”: 3, \“name\”: \“Lisa\”, \“salary\”: \“2000\”}” “https://localhost:3000/employees” Cheers

                  - Valentino

                    Try DigitalOcean for free

                    Click below to sign up and get $200 of credit to try our products over 60 days!

                    Sign up

                    Join the Tech Talk
                    Success! Thank you! Please check your email for further details.

                    Please complete your information!

                    Become a contributor for community

                    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                    DigitalOcean Documentation

                    Full documentation for every DigitalOcean product.

                    Resources for startups and SMBs

                    The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                    Get our newsletter

                    Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                    New accounts only. By submitting your email you agree to our Privacy Policy

                    The developer cloud

                    Scale up as you grow — whether you're running one virtual machine or ten thousand.

                    Get started for free

                    Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                    *This promotional offer applies to new accounts only.