Quick Tip: Mock REST APIs Using json-server
Can you quickly prototypify front-end applications without back-end? Creating even the most basic simulation API can be time-consuming and labor-intensive. The json-server library solves this problem by providing a quick and easy way to create complex RESTful APIs for development and testing.
This quick tip will teach you how to create a mock REST API using json-server, allowing you to get a full-featured API up and running in just 30 seconds.
Key Points
- json-server library can be used to quickly create complex RESTful APIs for development and testing, allowing developers to prototype the front end of their applications without a backend.
- json-server provides features such as filters, logical operators, paging and sorting, which helps create mock APIs that can be used to test front-ends with a large amount of fake data.
- With the faker.js module, developers can generate mock data for the API, which makes the development and testing process more efficient and closer to the actual situation.
Precautions
You should have the RESTful principle and basic knowledge of how to use the API.
You need the following tools:
- nodejs - json-server is built based on nodejs.
- curl – Used to test the routing of the simulated server.
Windows Users: The curl download page provides 32-bit and 64-bit versions of curl binaries that you can use to learn the examples in this article.
This tutorial assumes that you will use a bash-like terminal.
Installation
To install json-server, please 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 the RESTful API, a resource is an object with a type, associated data, relationships with other resources, and a set of methods to operate on it. For example, if you are creating an API for a movie, a movie is a resource. You can use your API to apply CRUD operations to this resource.
Let's create an API with /movies
resources.
Create resources
Create a file named db.json
and add the following 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 the server with the following command:
$ json-server --watch db.json
That's it! Now you have a movie API; you can get movies from this server, add new movies, delete movies, and many other actions.
To test our mock API, we can make HTTP requests using curl:
$ 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 will get two movies. Now to get a movie with id 1, just specify the id at the end of the URI: http://localhost:3000/movies/1
.
To add a movie to the server, you can send a POST request to the API with movie details. For example:
$ npm install -g json-server
This will return new movie data. To check if the record has been added successfully, let's try to get the movie with id 3:
{ "movies": [ {"id": 1, "name": "The Godfather", "director":"Francis Ford Coppola", "rating": 9.1}, {"id": 2, "name": "Casablanca", "director": "Michael Curtiz", "rating": 8.8} ] }
Similarly, you can use other HTTP verbs such as PUT and DELETE to access and modify data on this server. By convention, POST is used to create new entities, while PUT is used to update existing entities.
Note: PUT, POST and PATCH requests require a
Content-Type: application/json
header.
Function
json-server provides many useful features for the mock API that you need to build manually on the backend. Let's explore some of these features:
Filter
You can apply filters by appending them to the URI as a query string. For example, if you want to get the details of a movie called "Casablanca", you could send a GET request to the resource URI, append a question mark (?), and then the attribute name you want to filter and its value:
$ json-server --watch db.json
You can also combine multiple filters by adding an '&' between the filters (&'). For example, if we also want to filter by id in the example above, we can use:
$ curl -X GET "http://localhost:3000/movies"
operator
The API also provides you with logical operators to make filtering easier. You can use _gte
and _lte
as greater than and less than operators. You also have _ne
for excluding values from the response.
For example, if you want all movies with a rating greater than or equal to 9:
$ curl -X POST -H "Content-Type: application/json" -d '{ "id": 3, "name": "Inception", "director": "Christopher Nolan", "rating": 9.0 }' "http://localhost:3000/movies"
Note that you can combine multiple operators with numbers. So to get all movies with ratings between 5 and 7, you will make the following request:
$ curl -X GET "http://localhost:3000/movies/3"
Pagination
In the real world, you will process a lot of data. This data can be easily loaded into small chunks using json-server built-in pagination support (fixed 10 items per page).
For example, if you want to access page 3 of the movie API, send a GET request:
$ curl -X GET "http://localhost:3000/movies?name=Casablanca"
This will return to items 21-30.
Sorting
You can use the _sort
and _order
properties to request sorted data from the API. For example, if you want the movie list to be sorted in descending order by name (alphabetical order), you will send the following request:
$ curl -X GET "http://localhost:3000/movies?name=Casablanca&id=2"
json-server provides many other features. You can learn more about these and the above functions in the json-server documentation.
Generate simulation data for your API
It is no fun to use almost no data in the API to test the front-end. You can use modules like faker.js to create some sample data for your mock API.
Install the package with the following command:
$ curl -X GET "http://localhost:3000/movies?rating_gte=9"
Create a file called fake-data-generator.js
and enter the following in it:
$ curl -X GET "http://localhost:3000/movies?rating_gte=5&rating_lte=7"
Here, we created 1000 different fake movie entries, using faker to generate the movie title and director name. The score is created by generating a random number between 1 and 100 and dividing it by 10.
To create a db.json
file using this script, run the following command in the terminal:
$ npm install -g json-server
Now you have a database of 1000 movies. You now have a lot of fake data that can be used to develop and/or test your application.
Conclusion
You should now be able to quickly create your own mock API and add test data to it. The json-server library allows you to quickly prototypify front-end code without spending any time (almost) creating front-ends.
Will this tool become a part of your workflow? Or do you have any other ways to use it successfully? Please share your thoughts and suggestions in the comments below!
FAQs (FAQs) about using JSON Server to simulate REST APIs
What are the main advantages of using JSON Server to simulate REST API?
JSON Server provides a simple and fast way to set up fake REST APIs for development and testing purposes. It allows developers to create a complete REST API with CRUD (create, read, update, delete) operations in minutes. This can greatly speed up the development process because it eliminates the need to wait for the backend team to develop the actual API. In addition, JSON Server uses JSON files to store data, making it easy to modify the data and structure of the API.
How to install JSON Server?
JSON Server is a Node.js module, so you need to install Node.js and npm (Node Package Manager) on your system. After installing Node.js and npm, you can install JSON Server globally on your system using the following commands in the terminal or command prompt: npm install -g json-server
.
How to create a mock API using JSON Server?
To create a mock API using JSON Server, you first need to create a JSON file that will act as your database. This file should contain the number you wish to provide through the API
(Due to space limitations, subsequent FAQ content will be omitted. If necessary, please ask specific questions.)
The above is the detailed content of Quick Tip: Mock REST APIs 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

AI Hentai Generator
Generate AI Hentai for free.

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



Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

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...

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.

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

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...

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

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.
