json-server: npm package to mock a JSON REST API

What comes first - the front-end chicken or the API egg? Well, with the npm package json-server you can mock the egg to be able to develop your chicken independently.

What json-server does is expose a static json file as a REST API, complete with routes for single items, POSTing new items (that actually update your json file) and searching.

The easiest way to get json-server running is to install it globally, that way you don't even have to set up a node application.

$npm install -g json-server
$json-server -p 5000 myjson.json

Let's say your myjson.json looks like this:

{
  "products": [
    {
      "id": 1,
      "name": "iPhone 6",
      "price": 5000 
    }, 
    {
      "id": 2,
      "name": "Ghost subscription",
      "price": 5
    }],
  "customers": [
    {
      "id": 1,
      "name": "Anders Bornholm"
    }, 
    {
      "id": 2,
      "name": "The Metal Coder"
    }]
}

When run through json-server, all these routes are created for you:

http://localhost:5000/products
http://localhost:5000/products/{id}
http://localhost:5000/products?q={searchstring}
http://localhost:5000/customers
http://localhost:5000/customers/{id}
http://localhost:5000/customers?q={searchstring}

The search route (?q=) searches in all fields. The individual item routes (/{id}) automatically retrieves the object with the given id (the field name has to be "id").

If you POST to a route like http://localhost:5000/products an object is created or updated (if id is an existing id). json-server also accepts PUT, DELETE and PATCH.

You can also create nested relationships which create chained routes. For instance, if you add an orders collection that refers to products with a field name called "productId", a route that gets products in an order is automatically created:

http://localhost:5000/orders/1/products

With built-in support for CORS and jsonp you're not limited to running requests to the same domain as your frontend.

Happy prototyping!

comments powered by Disqus
Find me on Mastodon