Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 39 ยท Practice and Review

Mock REST APIs with JSON Server

Create a fake REST API from one db.json file with JSON Server, learn its routes, filters, sorting and pagination, and call it with fetch, with a runnable in-browser stand-in.

You have learned to call APIs. To practice everything (GET, POST, PATCH, DELETE, filters, pagination, error handling) you need an API to call, and often the real back end does not exist yet. JSON Server solves this: you write one JSON file, run one command, and get a complete REST API with persistence, in about a minute. Front-end developers use it for prototypes, tutorials, demos and tests, because the API appears before the real one is built.

This lesson shows how to set it up, what routes it creates, how to filter, sort and paginate, and how to use it with fetch. The editors on this site cannot run a Node server, so the runnable examples use a small stand-in written in JavaScript that behaves like JSON Server. The commands for your own machine are shown as read-only code.

From file to API in three steps

Write db.json Arrays become collections.
Run the server One command, one port.
Call it Plain fetch, real HTTP.
1 / 2

Setting it up

You need Node.js. Make a folder, create db.json, and run the server. This section describes the stable 0.17 line of JSON Server, which most tutorials use; a newer 1.x beta line exists and changes some query syntax (see the table below).

Terminal
mkdir mock-api && cd mock-api
npm init -y
npm install --save-dev json-server@0.17.4

db.json is plain JSON. Every top-level array becomes a collection of resources (with an id on each item), and every top-level object becomes a single resource:

JSON
{
  "posts": [
    { "id": 1, "title": "Hello JSON", "views": 100, "authorId": 1 },
    { "id": 2, "title": "Fetch basics", "views": 250, "authorId": 2 }
  ],
  "authors": [
    { "id": 1, "name": "Ada" },
    { "id": 2, "name": "Bob" }
  ],
  "profile": { "name": "demo" }
}

Start it with npx json-server --watch db.json --port 3000. The server prints the list of resources, and now http://localhost:3000/posts returns the array, http://localhost:3000/posts/1 the first post and http://localhost:3000/profile the single object. Put the command in package.json as "scripts": { "api": "json-server --watch db.json --port 3000" } so teammates run npm run api.

The routes you get

Request What it does Status
GET /posts all posts (with filters, below) 200
GET /posts/1 one post; 404 with {} if missing 200 / 404
POST /posts create; the server assigns the next id if you omit it 201
PUT /posts/1 replace the whole post 200
PATCH /posts/1 merge the fields you send 200
DELETE /posts/1 remove it (and the response body is {}) 200
GET /profile, PUT /profile, PATCH /profile the singular resource 200

Changes are written back to db.json, so they survive restarts. That is convenient, but remember to reset the file (or keep a copy in git) when you want a clean state. A good habit is a db.seed.json plus a script that copies it over db.json.

Query parameters do the work. Each row below is a request you can send with fetch:

Goal Query (JSON Server 0.17)
Equal /posts?authorId=1
Several values /posts?authorId=1&authorId=2
Range /posts?views_gte=100&views_lte=300
Not equal /posts?authorId_ne=1
Contains (regex-like) /posts?title_like=json
Full-text search /posts?q=fetch
Sort /posts?_sort=views&_order=desc
Page 2, 10 per page /posts?_page=2&_limit=10
Slice /posts?_start=10&_end=20
Include children /authors/1?_embed=posts
Include parent /posts/1?_expand=author
Nested route /authors/1/posts

Pagination answers with the data in the body and the metadata in headers: X-Total-Count is the total number of matches, and a Link header gives the first, prev, next and last URLs. That is why you can compute the number of pages without a second request. If you call the API from another origin, remember CORS: JSON Server allows it, and it exposes those two headers, so response.headers.get("X-Total-Count") works from the browser.

The 1.x beta line changes several of these. In it, range and not-equal filters use a colon (views:gt=100, authorId:ne=1), sorting is _sort=-views (a leading minus for descending), pagination uses _page and _per_page and the response body is an object with first, prev, next, last, pages, items and data, and ids it generates are strings. Always read the README of the version you installed; the idea is the same.

A stand-in you can run here

The function below plays the role of the server for this page. It keeps its data in memory, understands the 0.17 query syntax from the table, and answers with the same status codes. You call it exactly as you would call fetch.

JS A JSON Server stand-in and fetch calls

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Read the output line by line. Notice the 201 for POST with the new id assigned, the X-Total-Count that stays at the full number while a page shows only two items, and the 404 with an empty object body for a missing resource. These match what the real server does, so your code written against the stand-in works against JSON Server unchanged: you only replace api(...) with fetch("http://localhost:3000" + path, ...).

Using it from a real page

Once the server is running, your front end calls it like any API:

JavaScript
const API = "http://localhost:3000";

async function listPosts(page = 1) {
  const response = await fetch(`${API}/posts?_page=${page}&_limit=5&_sort=id&_order=desc`);
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  const total = Number(response.headers.get("X-Total-Count"));
  return { posts: await response.json(), pages: Math.ceil(total / 5) };
}

async function addPost(title) {
  const response = await fetch(`${API}/posts`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ title, views: 0 }),
  });
  return response.json();   // the saved post, including its new id
}

Keep the base URL in one constant (or an environment variable), so switching to the real API later is a one-line change. Because the shapes and status codes match a typical REST API, you can build the whole interface first, with loading states, error handling and pagination, and connect the real back end afterwards.

Useful extras

  • Delays and failures. The --delay 1000 option slows every response, which helps you test loading indicators. For random failures, add a tiny middleware file (--middlewares) that returns 500 for some requests so you can test your retry code from Retries and Backoff.
  • Custom routes. A routes.json file (--routes) rewrites URLs such as /api/* to /$1.
  • Static files. The public folder is served at /, so a prototype front end and its API can share a port and avoid CORS.
  • Generated data. If you need hundreds of records, build db.json with a small script (or a library like Faker) and run the server on the result.
  • Limits. There is no real authentication, validation or concurrency control. Treat JSON Server as a development tool and replace it before production.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In JSON Server, what makes a top-level array in db.json become a collection with REST routes?

    Each top-level array is a collection and each top-level object a single resource. Items in arrays should have an id.
  2. 2. Where does JSON Server 0.17 put the total number of matches when you request a page?

    Pagination metadata travels in headers, so the body stays a plain array.
  3. 3. Which request returns posts with at least 100 views, most viewed first (0.17 syntax)?

    _gte is the range suffix, _sort picks the field and _order the direction.
  4. 4. What status code does a successful POST to /posts return?

    The new resource is returned with the id the server assigned.
  5. 5. Why is JSON Server not suitable for production?

    It is a prototyping tool. Use a real back end for anything public.

Summary

  • JSON Server turns a db.json file into a REST API: arrays become collections, objects become single resources, and changes are saved to the file.
  • Routes follow REST: GET, POST, PUT, PATCH and DELETE with sensible status codes (201 for creation, 404 with {} for missing).
  • Query parameters filter (_gte, _lte, _ne, _like, q), sort (_sort, _order) and paginate (_page, _limit, with X-Total-Count in headers); the 1.x beta changes the syntax.
  • Build your UI against a mock first, keep the base URL in one place, and switch to the real API later.

Next: test your knowledge with the interview questions.