Wednesday, November 2, 2016

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:

Continue reading %Quick Tip: Mock REST APIs Using json-server%


by Ayush Gupta via SitePoint

No comments:

Post a Comment