Get a Fake REST API Up and Running Using json-server
In this tutorial, you'll see how to get started with setting up and using a fake REST API server using json-server, which you can use while developing mobile or web applications. This tutorial assumes that you have a basic knowledge of JSON and HTTP requests.
What Is REST?
REST stands for Representational State Transfer. It is an architecture style for designing connected applications. It uses simple HTTP to make communication between machines possible. So, instead of using a URL for manipulating some user information, REST sends an HTTP request like GET, POST, DELETE, etc. to a URL to manipulate data.
For example, instead of making a GET request to a URL like /deleteuser?id=10
, the request would be like DELETE /user/10
.
Why Do We Need a Fake REST API?
REST APIs form the back end for mobile and web applications. When developing applications, sometimes you won't have the REST APIs ready to be used for development purposes. To see the mobile or web app in action, we require a server which throws in some dummy JSON data.
That's when the fake REST API comes into the picture. json-server
provides the functionality to set up a fake REST API server with minimum effort.
Getting Started
To get started with using json-server
, install the package using Node Package Manager (npm).
npm install -g json-server<br>
Create a dummy JSON file with some data as per your requirement. For example, I need some JSON data with user information like id, name, location, etc. So I'll create a file called info.json
with the following JSON information:
{<br> "users": [{<br> "id": 1,<br> "name": "roy",<br> "location": "india"<br> }, {<br> "id": 2,<br> "name": "sam",<br> "location": "wales"<br> }]<br>}<br>
From the terminal, run the json server with info.json
as the data source, and you should have the REST API running at http://localhost:3000.
json-server info.json<br>
Testing the REST API Endpoints
Since our fake REST API server is up and running, let's see how to access the REST API using a client. I'm using the Postman REST client to make the API calls.
GET Request
Let's start by making a GET
request to the REST URL. Inside the json file, we have defined an endpoint users
which contains information related to users. On making a GET
request to the URL http://localhost:3000/users, it should display the existing data.

POST Request
In order to add new data to the existing data, we'll make a POST
request to the URL http://localhost:3000/users. Here's what the POST
request would look like:
Try doing a GET
request, and you should have the newly added data in the info.json
file.
[<br> {<br> "id": 1,<br> "name": "roy",<br> "location": "india"<br> },<br> {<br> "id": 2,<br> "name": "sam",<br> "location": "wales"<br> },<br> {<br> "name": "ii",<br> "location": "la",<br> "id": 7<br> },<br> {<br> "name": "Shona",<br> "location": "LA",<br> "id": 8<br> },<br> {<br> "name": "Shona",<br> "location": "LA",<br> "id": 9<br> }<br>]<br>
DELETE Request
To delete an entry from the json-server
data, you need to send a DELETE
request to the API endpoint with the user Id. For example, to delete the user with Id 1, you need to send a DELETE
request to the endpoint http://localhost:3000/users/1. Once it's deleted, try doing a GET
request, and the user with Id 1 should not be in the returned JSON.
PATCH Request
To update an existing entry, you need to send a PATCH
request with the details that need to be updated for that particular entry. For example, in order to update the details for a user with Id 2, we'll send a PATCH
request to the URL http://localhost:3000/users/2 as shown:

Searching json-server REST APIs
Using json-server
REST APIs, you can search through the data to find data based on certain criteria. For example, in order to find users with a particular name, you need to send a GET request to the REST API URL as shown:

As seen in the above image, sending a GET request to the URL http://localhost:3000/users?name=Shona would return the users with the name Shona
. Similarly, to search for users with any other fields, you need to add that field to the query string.
In order to execute a full text search across the REST API endpoint, you need to add the search string along with the parameter q
to the endpoint. For example, in order to search for users with info containing search string s
, the request would look like:
Handling Pagination
While displaying a paginated data grid, it would be required to fetch some data based on pagination. In such scenarios, json-server
provides the functionality to paginate the JSON data. By default, the count of data returned from json-server
is 10. We can explicitly define this limit using the _limit
parameter.
http://localhost:3000/users?_limit=5<br>
A GET request to the above URL would return five records. Now, to paginate the data, we need to add another parameter _page
to the URL. _page
defines the page which needs to be fetched on returning the data.
http://localhost:3000/users?_limit=5&_page=2<br>
A GET request to the above URL would return the second page of the data set with five records per page. By changing the _page
variable, we can fetch the required page records.
Handling Sorting
json-server
provides the functionality to sort the retrieved data. We can sort the data by providing the column name which needs to be sorted and the order in which the data needs to be sorted. By default, the data is sorted in ascending order. We can provide the column name in the endpoint URL using the keyword _sort
and define the order using the keyword _order
. Here is an example URL:
http://localhost:3000/users?_sort=id&_order=DESC<br>
The above URL would sort the data based on the column Id
, and it would be sorted in descending order.

Handling Operators
json-server
also provides the functionality to support operators like finding an entry with an Id in a range between two values or an entry matching a particular regular expression.
To find an entry within a particular range, we can make use of the _gte
and _lte
operators. For example, to find users with id greater than 3 and less than 5, make a GET request to the URL http://localhost:3000/users?id_gte=3&id_lte=5 as shown:

If we want to search for names starting with a certain letter, we can use regular expressions. For example, to search for names starting with the letters sa
, we'll make use of the _like
operator and make a GET
request to the URL http://localhost:3000/users?name_like=^sa.
Conclusion
In this tutorial, you saw how to use json-server
REST APIs to create a dummy database for quick use. You learnt how to get started with using json-server
and query the URL to add, update, modify, and delete data. You saw how to paginate, sort, and search the dummy data. You also saw how to use operators to search for entries using regular expressions.
Have you used json-server
or any other fake REST API server for dummy data creation? How was your experience? Do let us know your thoughts on the Envato forum.
The above is the detailed content of Get a Fake REST API Up and Running Using json-server. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...
