How to Quickly Mock REST APIs with json-server: A Step‑by‑Step Guide
This tutorial shows how to install json-server, create a db.json file, run the mock REST API, and perform GET and POST requests to simulate backend data, enabling front‑end developers to work without waiting for a real server.
In front‑end and back‑end development, communication often happens via web APIs using REST style and JSON structures. For example, a front‑end may request a list of articles with GET /post and receive JSON data.
When the back‑end cannot keep up with front‑end development speed, developers can mock the API by providing predefined JSON data.
json-server is a tool that serves a JSON file as a full‑featured REST API without writing any code. Install it globally: npm install -g json-server Create a db.json file, e.g.:
{
"posts": [
{ "id": 1, "title": "测试 json-server", "author": "dys" }
]
}Start the server: json-server db.json The console shows a greeting and the resources, e.g. http://localhost:3000/posts. Accessing that URL in a browser returns the posts array.
You can also retrieve a single item with GET http://localhost:3000/posts/1, or add a new item using a POST request. For example, sending the following JSON payload:
{
"id": 2,
"title": "测试 post",
"author": "dys"
}adds a new post, which then appears when you request http://localhost:3000/posts again.
The image below shows the POST request in a HTTP client.
json-server also offers many advanced features; see its official repository for more details.
Project homepage: https://github.com/typicode/json-server
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
