Quick Tip: Mock REST APIs Using json-server

Share this article

Quick Tip: Mock REST APIs Using json-server

Sometimes you need to prototype the front-end of your application without a back-end in place. Creating even a basic mock API to develop against can be time-consuming. The json-server library solves this problem for you by providing a fast and easy way to create complex RESTful APIs for development and testing.

This quick tip will teach you how to create mock REST APIs using json-server, allowing you to get a fully-featured API up and running in as little as 30 seconds.

Prerequisites

You should have basic knowledge of RESTful principles and how to consume APIs.

You’ll need the following tools:

  • nodejs – json-server is built on top of nodejs.
  • curl – to test the routes of your mock server.

Windows users: There are curl binaries available in 32-bit and 64-bit varieties from the curl downloads page that will allow you to follow along with the examples in this article.

This tutorial assumes you’ll be using a bash-like terminal.

Installation

To install json-server, open your terminal and enter:

$ npm install -g json-server

This will install json-server globally on your system so that you can start the server from any directory you like.

Resources

In a RESTful API, a resource is an object with a type, associated data, relationships to other resources, and a set of methods that operate on it. For example, if you are creating an API for movies, a movie would be a resource. You can apply CRUD operations on this resource using your API.

Let’s create an API with a /movies resource.

Creating a Resource

Create a file called db.json and add the following content to it:

{
  "movies": [
    {"id": 1, "name": "The Godfather", "director":"Francis Ford Coppola", "rating": 9.1},
    {"id": 2, "name": "Casablanca", "director": "Michael Curtiz", "rating": 8.8}
  ]
}

After saving the file, start your server with the following command:

$ json-server --watch db.json

That’s it! Now you have a movies API; you can fetch movies from this server, add new movies, delete movies, and a bunch of other stuff.

To test our mock API, we can use curl to make an HTTP request:

$ curl -X GET "http://localhost:3000/movies"

This will return a list of all the movies you have on this server. In the above case, you’ll get two movies. Now to get the movie with the id of 1, just specify the id at the end of the URI: http://localhost:3000/movies/1.

To add movies to the server, you can send a POST request to the API with the movie details. For example:

$ curl -X POST -H "Content-Type: application/json" -d '{
  "id": 3,
  "name": "Inception",
  "director": "Christopher Nolan",
  "rating": 9.0
}' "http://localhost:3000/movies"

This will respond with the new movie data. To check the record was successfully added, let’s try getting the movie with id 3:

$ curl -X GET "http://localhost:3000/movies/3"

Similarly, you can use other HTTP verbs like PUT and DELETE to access and modify data on this server. By convention, POST is used for creating new entities while PUT is used for updating existing entities.

Note: PUT, POST and PATCH requests need to have a Content-Type: application/json header set.

Features

json-server provides a lot of useful features for the mock API that you need to manually build on a back-end. Let us explore some of these features:

Filters

You can apply filters to your requests by appending them to the URI as a query string. For example, if you want to get the details of a movie named “Casablanca”, you can send a GET request to your resource URI, appending a question mark (?) followed by the property name you want to filter by and its value:

$ curl -X GET "http://localhost:3000/movies?name=Casablanca"

You can also combine multiple filters by adding an ampersand (&) between different filters. For example, if we also want to filter by id in above example, we could use:

$ curl -X GET "http://localhost:3000/movies?name=Casablanca&id=2"

Operators

The API also provides you with logical operators to make filtering easy. You can use _gte and _lte as greater than and less than operators. You also have _ne for excluding a value from the response.

For example, if you wanted all movies whose ratings are greater than or equal to 9:

$ curl -X GET "http://localhost:3000/movies?rating_gte=9"

Note that you can combine multiple operators using the ampersand sign. So to get all movies which have ratings between 5 and 7, you’d make the following request:

$ curl -X GET "http://localhost:3000/movies?rating_gte=5&rating_lte=7"

Pagination

In a real world scenario, you’ll be dealing with lots of data. Loading this data in bite-sized chucks is easy with json-server’s built-in pagination support, which is fixed at 10 items per page.

For example, if you want to access page 3 of your movies API, send a GET request:

$ curl -X GET "http://localhost:3000/movies?_page=3"

This will respond with items 21-30.

Sorting

You can ask for sorted data from your API using the _sort and _order properties. For example, if you want the list of movies to be sorted by name (alphabetically) in descending order, then you’ll send the following request:

$ curl -X GET "http://localhost:3000/movies?_sort=name&order=DESC"

There are many other features that json-server provides. You can explore those and the above features in detail in the json-server documentation.

Generating Mock Data for Your API

Testing front-ends with almost no data in your API is no fun. You can create some sample data for your mock API using a module like faker.js.

Install the package using:

$ npm install faker

Now create a file called fake-data-generator.js and enter the following in it:

var faker = require('faker');

var db = { movies: [] };

for (var i=1; i<=1000; i++) {
  db.movies.push({
    id: i,
    name: faker.random.words(),
    director: faker.name.firstName() + ' ' + faker.name.lastName(),
    rating: Math.floor(Math.random()*100+1)/10
  });
}

console.log(JSON.stringify(db));

Here, we’re creating 1000 different fake movie entries, with faker being used to generate the movie titles and director names. The ratings are created by generating a random number between 1 and 100, and dividing by 10.

To create a db.json file using this script, run the following command in your terminal:

$ node fake-data-generator.js > db.json

Now you have a database of 1000 movies. You now have a large amount of fake data you can use to develop and/or test your apps.

Conclusion

You should now be able to quickly create your own mock APIs and add test data to them. The json-server library allows you to rapidly prototype front-end code without investing any time (almost) in creating a back-end upfront.

Is this tool going to become part of your workflow, or do you have another method you’ve been using successfully? Share your thoughts and suggestions in the comments below!

Frequently Asked Questions (FAQs) about Mock REST APIs Using JSON Server

What is the main advantage of using JSON Server for mocking REST APIs?

JSON Server provides a simple and quick way to set up a fake REST API for development and testing purposes. It allows developers to create a full-fledged REST API with CRUD (Create, Read, Update, Delete) operations in a matter of minutes. This can significantly speed up the development process, as it eliminates the need to wait for the back-end team to develop the actual API. Moreover, JSON Server uses a JSON file to store data, making it easy to modify the data and structure of the API.

How can I install JSON Server?

JSON Server is a Node.js module, so you need to have Node.js and npm (Node Package Manager) installed on your system. Once you have Node.js and npm, you can install JSON Server globally on your system using the following command in your terminal or command prompt: npm install -g json-server.

How can I create a mock API with JSON Server?

To create a mock API with JSON Server, you first need to create a JSON file that will act as your database. This file should contain the data you want to serve through your API. Once you have your JSON file, you can start JSON Server with the following command: json-server --watch db.json, where db.json is the name of your JSON file.

Can I customize the routes in JSON Server?

Yes, JSON Server allows you to customize the routes. You can do this by creating a routes.json file and defining your custom routes in it. Then, you can start JSON Server with the custom routes using the following command: json-server --watch db.json --routes routes.json.

How can I add delay to responses in JSON Server?

JSON Server provides an option to add delay to responses. This can be useful for simulating real-world scenarios where network latency is involved. You can add delay to responses using the --delay option when starting JSON Server. For example, the following command will add a delay of 2 seconds to all responses: json-server --watch db.json --delay 2000.

Can I use JSON Server in production?

JSON Server is primarily intended for development and testing purposes. It is not recommended to use it in production as it lacks many features that a production-grade server should have, such as authentication, authorization, and data validation.

How can I secure my JSON Server?

JSON Server does not provide built-in security features. However, you can add a layer of security by using it behind a proxy server. The proxy server can handle authentication, authorization, and other security-related tasks.

Can I host my JSON Server on the cloud?

Yes, you can host your JSON Server on the cloud. Many cloud service providers, such as Heroku, allow you to host Node.js applications, which includes JSON Server.

Can I use JSON Server with other programming languages?

JSON Server is a Node.js module, so it is primarily intended to be used with JavaScript. However, since it creates a REST API, you can interact with it using any programming language that can send HTTP requests.

How can I contribute to JSON Server?

JSON Server is an open-source project, so you can contribute to it by submitting pull requests on its GitHub repository. You can also report issues, suggest new features, or improve the documentation.

Ayush GuptaAyush Gupta
View Author

I'm a computer engineering student from India who loves web development. Aside from working on the web, I have a particular interest in low level computing. When I'm not online, you can find me reading books or on the football field. Check out my blog!

JS Quick TipsNode-JS-Tutorialsnode.jsprototypingrest api
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week