Custom routes json-server


This post talks how to setup json-server to use custom id and routes. In case you dont know, json-server allows you to run a fake HTTP server with zero coding in no time. This is a common solution to allow UI team to work while REST APIs are being developed by the backend team.

To use json-server, you need to install it on your machine using the following command.

$ npm install -g json-server

Now that json-server is installed you can make it run a fake HTTP server. Before we do that lets understand our requirement.

Lets suppose that we are want to create fake HTTP server for user preferences API. The server will expose a CRUD REST API at /api/v1/users/1/preferences.

The way json-server works is that it needs a db.json with some data.

{ "preferences": [ { "appId": 1, "timezone": "IST", "email": "daily" }, { "appId": 2, "timezone": "EST", "email": "weekly" }, { "appId": 3, "timezone": "PST", "email": "never" } ] }

You can run fake HTTP server by running following command.

$ json-server db.json

This will start the server at //localhost:3000

You can view all the preferences object by using cURL or something similar.

$ curl //localhost:3000/preferences

[
{
"appId": 1,
"timezone": "IST",
"email": "daily"
},
{
"appId": 2,
"timezone": "EST",
"email": "weekly"
},
{
"appId": 3,
"timezone": "PST",
"email": "never"
}
]

You got all the three records.

To view a specific record i.e. record with appId 1 you will be expecting that you could make following cURL call. But, it will return empty response.

$ curl //localhost:3000/preferences/1 {}

To make json-server understand that appId is the id of the record we will have to restart json-server passing it id attribute as shown below.

$ json-server db.json --id appId

Now, if you make cURL request you will get valid response as shown below.

$ curl //localhost:3000/preferences/1

{
"appId": 1,
"timezone": "IST",
"email": "daily"
}

We mentioned earlier that we want to use a different REST API route //localhost:3000/api/v1/users/1/preferences instead of //localhost:3000/preferences/1.

To do that, we will have to create another file routes.json and define our custom mapping as shown below.

{
"/api/v1/users/:appId/preferences": "/preferences/:appId"
}

Now, you need to restart the json-server with the routes option.

$ json-server --id appId db.json --routes routes.json

You should be able to access the API at the custom route as shown below.

$ curl //localhost:3000/api/v1/users/1/preferences

{
"appId": 1,
"timezone": "IST",
"email": "daily"
}

Share this:

  • Reddit
  • Twitter
  • Email
  • LinkedIn
  • Pinterest
  • Pocket
  • WhatsApp
  • Facebook
  • Telegram

Like this:

Like Loading...

Related

Video liên quan

Chủ Đề