Tutorial on How to Use json-server

Posted in Uncategorized

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

In this tutorial, we have install json-server node module to a simple Node app to see how json-server can be used to output json via an URL. So it can be used for mock REST api with test data.

npm install -g json-server

Create json data in “api/movies.json” that looks like …

Start up the json-server on the command line on port 3001 with …

json-server api/movies.json –port 3001

In your browser, http://localhost:3001 will tell you if your json-server is up or not…

On http://localhost:3001/movies will give you back the movie data …

The url http://localhost:3001/movies/2 will give the movie with “id” value of 2. It specifically looks for the “key” of “id”.

In other words, it is equivalent to …

http://localhost:3001/movies?id=2

You can query for title like …

http://localhost:3001/movies?title=Star%20Wars

Note the %20 and the lack of quotes.

You can do an “and” query like …

http://localhost:3001/movies?title=Star%20Wars&year=1977

Using Routes

Let’s say that you want to more closely match your backend api URL structure and use URL of the format …

http://localhost:3001/backend/rest/movies?year=1977

Add a routes.json to the “api” folder …

It means that the physical “api” folder is mapped to url structure “/backend/rest”

Now you access the http endpoints like …

http://localhost:3001/backend/rest/movies?year=1977

in addition to how you have been accessing it.

There is more features with json-server that we won’t get into in this intro tutorial — namely, you can sort and order and parameterize the routes as well as write JS to generate data.


Related Posts

Tags

Share This