Creating a RESTful API with JSON Server in Node.js: A Comprehensive Guide.
Agu O. Wisdom
Posted on March 27, 2023
Introduction
JSON Server is a powerful NPM package that allows you to quickly and easily set up a RESTful API with zero coding. It's a lightweight and flexible tool that can be used to simulate a full backend API, making it ideal for prototyping, testing, and developing small to medium-sized applications.
With JSON Server, you can create a fully functional API by just writing a simple JSON file. The server will then use this file to generate a RESTful API, complete with all the necessary endpoints for GET, POST, PUT, DELETE requests, and more. This makes it incredibly easy to get up and running quickly, without having to worry about the complexities of building a backend API from scratch.
In this beginner's guide, I'll show you everything you need to know to get started with JSON Server. I'll walk you through the installation process, show you how to create a JSON file to define your data structure, and demonstrate how to use the API endpoints to retrieve, update, and delete data. Whether you're a seasoned developer or just starting out, this guide will provide you with everything you need to know to get started with JSON Server.
By the end of this guide, you'll have a solid understanding of JSON Server and how it can be used to create a RESTful API with minimal effort. So, let's get started!
Course Structure
This article is divided into the following sections, each covering a key aspect of creating a simple JSON Server file that can be used as a database and supports various API features:
Retrieving all data from the endpoint: Learn how to retrieve a list of items from your JSON Server file and return them as a JSON object.
Querying by ID: Discover how to retrieve a specific item from your JSON Server file by its unique ID.
Filtering: Learn how to filter items in your JSON Server file based on specific criteria.
Sorting: Learn how to sort items in your JSON Server file based on specific fields.
Pagination: Learn how to retrieve a subset of items from your JSON Server file based on page size and page number.
Consclusion: By the end of this article, you will have a solid understanding of how to create a simple JSON Server file that can be used as a database and supports various API features.
Prerequisite
To get the most out of this tutorial, it is necessary that you have the following:
Basic understanding of how a RESTful API works: JSON Server is a tool that allows you to create a RESTful API, so it's essential that you have a basic understanding of how APIs work before diving into this tutorial.
Node.js Installed: JSON Server is built on top of Node.js, so it's essential that you have Node.js installed on your machine before starting. If you don't already have it installed, you can download it from the official Node.js website.
With these two prerequisites in place, you'll be ready to dive into this tutorial and start creating your own RESTful API with JSON Server.
Building a JSON Server API: A Step-by-Step Guide to Setting up, Querying, and Managing Your Data.
This section will guide you through the process of building a JSON Server API. First, let's start by setting up our development environment.
Setting up a JSON Server project.
-
Installing Json Server: Before we can start building our JSON Server API, we need to install JSON Server. JSON Server can be installed using Node.js and the
npm
package manager.
To install JSON Server, we need to, first, initialize our project. Open your terminal or command prompt and run the following command:
npm init -y
npm init -y
is a command that initializes a new Node.js project with default settings, without prompting the user for any input.
The -y
flag tells npm to use default settings for all options, creating a package.json file with default values such as the project name, version, and entry point.
This command is often used at the beginning of a new project to quickly set up a basic project structure and package management for the project. Once that is out of the way, let's now install Json Server. Run the following command in your terminal:
npm install -g json-server
This will install JSON Server globally on your system, making it available for use in any project.
However, if you don't want to install it globally, you can skip the -g
flag
Once the installation is complete, you can verify that JSON Server is installed by running the following command in your terminal:
json-server --version
You should see something like this:
bigwiz@bigwiz:~/Documents/jsonwebserver$ json-server --version
0.17.3
- Creating a db.json file: The second step in setting up a JSON Server Project is to create a JSON file that will serve as the data source for the server. This file will contain the data that the server will expose through its RESTful API.
The JSON file should be structured as an array of objects, with each object representing a record in the data set. For example, if you were creating a JSON Server to serve data for an ecommerce site, each object in the JSON file might represent a product, with properties like id
title
, description
, price
and category
.
Once the JSON file is created, it can be used as the data source for the JSON Server.
Now let's create a db.json
file with an array of 20 products for our project. Open your text editor and create a file call db.json
and insert the following data into it:
{
"products": [
{
"id": 1,
"title": "product 1",
"price": 300,
"category": "cars",
"description": "Product 1 description"
},
{
"id": 2,
"title": "product 2",
"price": 200,
"category": "accessories",
"description": "Product 2 description"
},
{
"id": 3,
"title": "product 3",
"price": 600,
"category": "gadgets",
"description": "Product 3 description"
},
{
"id": 4,
"title": "product 4",
"price": 400,
"category": "accessories",
"description": "Product 4 description"
},
{
"id": 5,
"title": "product 5",
"price": 500,
"category": "gadgets",
"description": "Product 5 description"
},
{
"id": 6,
"title": "product 6",
"price": 300,
"category": "accessories",
"description": "Product 6 description"
},
{
"id": 7,
"title": "product 7",
"price": 200,
"category": "jeweries",
"description": "Product 7 description"
},
{
"id": 8,
"title": "product 8",
"price": 600,
"category": "gadgets",
"description": "Product 8 description"
},
{
"id": 9,
"title": "product 9",
"price": 600,
"category": "accessories",
"description": "Product 9 description"
},
{
"id": 10,
"title": "product 10",
"price": 500,
"category": "gadgets",
"description": "Product 10 description"
},
{
"id": 11,
"title": "product 11",
"price": 300,
"category": "foods",
"description": "Product 11 description"
},
{
"id": 12,
"title": "product 12",
"price": 200,
"category": "accessories",
"description": "Product 12 description"
},
{
"id": 13,
"title": "product 13",
"price": 600,
"category": "cars",
"description": "Product 13 description"
},
{
"id": 14,
"title": "product 14",
"price": 900,
"category": "accessories",
"description": "Product 14 description"
},
{
"id": 15,
"title": "product 15",
"price": 700,
"category": "jeweries",
"description": "Product 15 description"
},
{
"id": 16,
"title": "product 16",
"price": 300,
"category": "clothes",
"description": "Product 16 description"
},
{
"id": 17,
"title": "product 17",
"price": 400,
"category": "foods",
"description": "Product 17 description"
},
{
"id": 18,
"title": "product 18",
"price": 600,
"category": "gadgets",
"description": "Product 18 description"
},
{
"id": 19,
"title": "product 19",
"price": 400,
"category": "accessories",
"description": "Product 19 description"
},
{
"id": 20,
"title": "product 20",
"price": 1000,
"category": "gadgets",
"description": "Product 20 description"
}
]
}
After creating the db.json file, the next step is to use it as the data source for the JSON Server.
To use the db.json file as the data source, you need to start the JSON Server by running the following command in your terminal or command prompt:
json-server --watch db.json
This command starts the JSON Server and tells it to watch the db.json file for changes. Any changes you make to the db.json file will be immediately reflected in the API provided by the server.
Once the server is running, you can access the API by navigating to http://localhost:3000/ in your web browser. This will display a list of the available endpoints for your API. You can then use these endpoints to fetch and manipulate the data stored in your db.json file.
Your commandline should display something like this:
\{^_^}/ hi!
Loading db.json
Done
Resources
http://localhost:3000/products
Home
http://localhost:3000
Type s + enter at any time to create a snapshot of the database
Watching...
In the next section, we'll start querying our Json-Server database.
Retrieving all data from the "products" endpoint
Making a GET
request is perhaps the simplest, all you have to do is navigate to http://localhost:3000/products
and you will get a list of all the products. As you can see, with zero coding we have set up a RESTful API
. How sweet is that 😉.
Querying by ID
Just like retrieving all the products, We can retrieve a particular product by it's ID
, by simply navigating to http://localhost:3000/products/id
. Let's assume we want to get the product with the ID
of 12
we can simply navigate to http://localhost:3000/products/12
and this will return a single object of the product with id of 12.
Filtering
In this section, we will see how to filter data when making a GET
request. Assuming we are building an e-commerce website and the user should have an option to filter a list of product by category. How do we do that with Json Server?. Well that is very simple. All we need to do is navigate to the URL
which is http://localhost:3000/products
and append a query parameter of the property we want to filter by like so:
localhost:3000/products?category=cars
This will return an array of all the products under the cars category. It's as simple as that.
Sorting
In an e-commerce website, a common requirement is being able to sort
the products, lower-to-high or higher-to-low. In our case, let's say we need to sort this products by the price
property. How do we do that? again it is very simple. Let me show how to do that. To sort
products by the price
property, all we need to do is navigate localhost:3000/products
and append a query parameter of _sort
and set it's value to the property we want to sort by, in this case, it is the price property:
localhost:3000/products?_sort=price
When we make this request, product will be sorted in the ASC
order of price. From the lowest all the way to the highest. By deffault, products is sorted in the ASC order, if you want to to sort by DESC
order, all you need to do is append &_order=desc
to localhost:3000/products?_sort=price
like so:
localhost:3000/products?_sort=price&_order=desc
Now th price will go from the highest to the lowest.
Pagination
In this section, let's learn how Json-Sever supports pagination. Right now, If we navigate to localhost:3000/products
you will get a list of all the products. But when you are displaying a list of products or if you have a table, pagination is something you might have to support.
To Paginate the data, we append ?_page
then we assign a page number. By diffualt, each page returns a list of 10 Items. For example if we specify localhost:3000/products?_page=1
in the URL, by diffualt we will get an array of the first 10 products in our db.json
file. Likewise, if we specify the page as 2 we will get the next 10 products and so on.
We can also limit the number of product we want to retrieve like so:
localhost:3000/products?_page=1&_limit=6
This will return an array of the first 6 products in the db.json file
. As you can see, it is very easy to serve paginated data with Json Server.
Conclusion
Using JSON server is an easy and efficient way to set up a mock API for your front-end applications. By following the steps outlined in this article, you can quickly create a fake API that closely mimics the behavior of a real one, and test your code without having to worry about the complexities of the backend. So if you're a front-end developer looking for a convenient way to mock an API, you should give JSON server a try.
Posted on March 27, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.