a blog for those who code

Thursday 9 February 2017

Fake REST API for FrontEnd Development

In this post we will be discussing about faking or mocking REST API for frontend development. Sometimes when you are building an application without back-end in place, you need to mock API to save time. This json-server save some time by providing an easy way to create Restful APIs for development and testing.

Why You Need to Mock or Fake API

There are a number of reasons where you want to mock or fake Restful API's and they are :

1. API not ready - There might be situations where you do not have the API ready at that moment when you have started working on a project. So then your best bet is to mock the API to start the development and not waste time. It a
2. Work Offline - If you are not inside any network, whether your intranet or internet than you can possibly mock api's and continue working.

At first you need to install npm and node.js to start working with json-server. You also should know the basic knowledge of Restful APIs and how to consume it on the front-end.


You need to install json-server using the command npm install -g json-server, which will install the json-server globally thus you can start the server from any directory you like.

Creating JSON file - db.json

Next thing is to create a resource file which contains the details of the API which we will be using. We will using the API /posts and the contents of it are shown below :

 "posts": [
  {"id":1, "title":"CodingDefined.com First Post", "date": "01/01/2017"},
  {"id":2, "title":"CodingDefined.com Second Post", "date": "01/02/2017"},
  {"id":3, "title":"CodingDefined.com Third Post", "date": "01/03/2017"}

Now you can run the server using the command : json-server --watch db.json. It will start the server on port 3000 and the resources would be found at http://localhost:3000/posts as shown below :

Start json-server using command json-server --watch db.json

Get all the posts using end point http://localhost:3000/posts

Different Routes as per the Restful API's are :

GET /posts -to get all posts
GET /posts/1 -to get posts of id=1
POST /posts -to add new post
PUT /posts/1 -to modify post of id=1
DELETE /posts/1 -to delete posts of id=1

Now just you have to create an AJAX call and you should be able to quickly create your own mock API's and add test data to them. Please Like and Share CodingDefined.com blog, if you find it interesting and helpful.

No comments:

Post a Comment