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-serverNow 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.jsonThis will start the server at http://localhost:3000 You can view all the preferences object by using cURL or something similar. $ curl http://localhost:3000/preferences[ 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 http://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 appIdNow, if you make cURL request you will get valid response as shown below. $ curl http://localhost:3000/preferences/1{ We mentioned earlier that we want to use a different REST API route http://localhost:3000/api/v1/users/1/preferences instead of http://localhost:3000/preferences/1. To do that, we will have to create another file routes.json and define our custom mapping as shown below. { Now, you need to restart the json-server with the routes option. $ json-server --id appId db.json --routes routes.jsonYou should be able to access the API at the custom route as shown below. $ curl http://localhost:3000/api/v1/users/1/preferences{ Share this:
Like this:Like Loading... Related |