search
HomeWeb Front-endJS TutorialQuick Tip: Mock REST APIs Using json-server

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools