JavaScript
Article
By Ayush Gupta

Quick Tip: Mock REST APIs Using json-server

By Ayush Gupta

This article was peer reviewed by Vildan Softic. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!

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.

--ADVERTISEMENT--

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!

  • How to using CURL ?

  • error!

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

    • Ayush Gupta

      Hi @xgqfrms:disqus,
      Did you install all the prerequisites mentioned and create a db.json file? Also let the server run in the background when you are sending a cURL request.

  • why not support send images ?

  • TimA11y

    Thanks for your quick replies to my questions. I actually have some JSON data I wouldn’t mind trying this on. I’ll take a look this weekend and try the update to see how it works!

  • Porkopek

    Thank you very much. I have played with it 10 min and it’s a great tool.

  • Osvaldo Maria

    Thanks loads .. this seems to be very useful

Recommended
Sponsors
Get the latest in JavaScript, once a week, for free.