Skip to Content
Technical Articles

How to use JSON Server to mock REST API in local environment

During frontend development in local environment, you may want to have a fake REST API to test your stuff based on mock data. JSON Server is such a tool that you can have any desired REST API running with zero coding. The only thing you need to prepare is json files to store data which are assumed to be returned by the fake API.

1. Install JSON Server.

Open your Terminal. Execute the following command.

npm install -g json-server

2. Go to the folder where you want to store the json files. Create json file as per the response body of the API you want to mock. For example, you can create a following article.json file.

{
    "article": [
        {
            "id": "12346",
            "provider": "Mindtouch",
            "title": "kaka test",
            "content": "This guide provides an overview of product features and related technologies",
            "tag": [
                "test",
                "coffee maker"
            ]
        }
    ]
}

3. Start JSON Server with the specified json file. Normally you need to specify a port number to avoid conflict with existing ports you are going to use.

json-server --watch article.json --port 3002

If you see “Watcdhing …”, it means it’s up and running.

4. Verify the mocked API. Now if you go to http://localhost:3002/article in browser, you’ll get following result.

The Terminal shows status code and execution time for processing this request.

5.If you want to have additional fake API, repeat above steps but specify different ports.

 

More complex usage and customization of json-server, go to following web site.

https://github.com/typicode/json-server

 

Be the first to leave a comment
You must be Logged on to comment or reply to a post.