Convert Figma logo to code with AI

typicode logojson-server

Get a full fake REST API with zero coding in less than 30 seconds (seriously)

75,651
7,266
75,651
717

Top Related Projects

8,334

Mockoon is the easiest and quickest way to run mock APIs locally. No remote deployment, no account required, open source.

13,114

HTTP server mocking and expectations library for Node.js

A client-side server to build, test and share your JavaScript app

18,043

Industry standard API mocking for JavaScript.

Quick Overview

JSON Server is a full fake REST API with zero coding in less than 30 seconds. It's designed to prototype and mock APIs quickly, allowing front-end developers to work independently from back-end teams. JSON Server creates a complete REST API from a JSON file or JavaScript object.

Pros

  • Quick setup and zero configuration required
  • Supports RESTful operations (GET, POST, PUT, PATCH, DELETE)
  • Provides features like pagination, filtering, and sorting out of the box
  • Can be extended with custom routes and middlewares

Cons

  • Not suitable for production environments
  • Limited to JSON data format
  • Lacks advanced features of real databases (e.g., complex queries, transactions)
  • May not accurately represent the behavior of a real API in all scenarios

Code Examples

  1. Creating a basic server:
// db.json
{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
}
  1. Starting the server:
json-server --watch db.json
  1. Making requests to the API:
// GET request
fetch('http://localhost:3000/posts/1')
  .then(response => response.json())
  .then(data => console.log(data))

// POST request
fetch('http://localhost:3000/posts', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ title: 'New Post', author: 'John Doe' })
})
  .then(response => response.json())
  .then(data => console.log(data))

Getting Started

  1. Install JSON Server globally:

    npm install -g json-server
    
  2. Create a db.json file with some data:

    {
      "posts": [
        { "id": 1, "title": "First Post", "author": "John Doe" }
      ]
    }
    
  3. Start JSON Server:

    json-server --watch db.json
    
  4. Access your API at http://localhost:3000/posts

Competitor Comparisons

8,334

Mockoon is the easiest and quickest way to run mock APIs locally. No remote deployment, no account required, open source.

Pros of Mockoon

  • User-friendly GUI for creating and managing mock APIs
  • Supports more advanced features like proxy mode and CORS settings
  • Allows for easy import/export of API environments

Cons of Mockoon

  • Requires installation of desktop application
  • May have a steeper learning curve for beginners
  • Limited scripting capabilities compared to JSON Server

Code Comparison

Mockoon (Configuration in JSON):

{
  "uuid": "mockoon-environment-id",
  "lastMigration": 19,
  "name": "My API",
  "endpointPrefix": "api",
  "latency": 0,
  "port": 3000,
  "routes": [
    {
      "uuid": "route-id",
      "documentation": "Get users",
      "method": "get",
      "endpoint": "users",
      "responses": [
        {
          "uuid": "response-id",
          "body": "[\n  {\n    \"id\": 1,\n    \"name\": \"John Doe\"\n  }\n]",
          "latency": 0,
          "statusCode": 200,
          "label": "",
          "headers": [],
          "filePath": "",
          "sendFileAsBody": false,
          "rules": [],
          "rulesOperator": "OR",
          "disableTemplating": false,
          "fallbackTo404": false
        }
      ],
      "enabled": true
    }
  ]
}

JSON Server (db.json):

{
  "users": [
    {
      "id": 1,
      "name": "John Doe"
    }
  ]
13,114

HTTP server mocking and expectations library for Node.js

Pros of nock

  • Specifically designed for HTTP mocking in Node.js tests
  • Allows for more granular control over request matching and response generation
  • Supports dynamic responses based on request parameters

Cons of nock

  • Limited to Node.js environment, not suitable for frontend development
  • Steeper learning curve due to more complex API
  • Requires more setup and teardown in test files

Code Comparison

nock:

const scope = nock('https://api.example.com')
  .get('/users')
  .reply(200, [{ id: 1, name: 'John' }]);

json-server:

// db.json
{
  "users": [
    { "id": 1, "name": "John" }
  ]
}

Key Differences

  • nock is primarily for testing, while json-server is for rapid prototyping and development
  • json-server provides a full REST API with minimal setup, nock requires more configuration
  • nock offers more flexibility in request matching and response generation
  • json-server can be used as a standalone server, while nock is integrated into test files

Use Cases

  • Use nock for unit testing HTTP requests in Node.js applications
  • Choose json-server for quickly mocking a REST API during frontend development
  • nock is better for complex scenarios requiring dynamic responses
  • json-server is ideal for projects needing a persistent mock database

A client-side server to build, test and share your JavaScript app

Pros of Mirage JS

  • More flexible and powerful for complex scenarios
  • Seamless integration with JavaScript testing frameworks
  • Supports dynamic data generation and relationships

Cons of Mirage JS

  • Steeper learning curve
  • Requires more setup and configuration
  • Less suitable for quick prototyping or simple APIs

Code Comparison

JSON Server:

// db.json
{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ]
}

// Start server
json-server --watch db.json

Mirage JS:

import { createServer, Model } from "miragejs"

createServer({
  models: {
    post: Model,
  },
  seeds(server) {
    server.create("post", { title: "Mirage JS", author: "Sam Selikoff" })
  },
  routes() {
    this.namespace = "api"
    this.get("/posts", (schema) => schema.posts.all())
  },
})

Summary

JSON Server is simpler and quicker to set up for basic mock APIs, while Mirage JS offers more advanced features and better integration with JavaScript applications and testing environments. JSON Server is ideal for rapid prototyping and simple scenarios, whereas Mirage JS shines in complex, dynamic API mocking situations, especially in test-driven development.

18,043

Industry standard API mocking for JavaScript.

Pros of MSW

  • Integrates seamlessly with existing JavaScript test suites
  • Supports mocking both REST and GraphQL APIs
  • Can be used in both browser and Node.js environments

Cons of MSW

  • Steeper learning curve due to more complex setup
  • Requires additional configuration for certain frameworks
  • May not be suitable for non-JavaScript projects

Code Comparison

MSW:

import { rest } from 'msw'
import { setupServer } from 'msw/node'

const server = setupServer(
  rest.get('/api/users', (req, res, ctx) => {
    return res(ctx.json([{ id: 1, name: 'John' }]))
  })
)

JSON Server:

// db.json
{
  "users": [
    { "id": 1, "name": "John" }
  ]
}

// Start JSON Server
json-server --watch db.json

Key Differences

  • MSW mocks at the network level, while JSON Server creates a full REST API
  • MSW is more flexible for complex scenarios and testing, while JSON Server is simpler to set up
  • JSON Server provides a real HTTP server, whereas MSW intercepts requests without a separate server

Use Cases

  • MSW: Ideal for testing and development of complex applications, especially those using modern JavaScript frameworks
  • JSON Server: Better suited for quick prototyping, simple backend mocking, and non-JavaScript projects

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

JSON-Server

Node.js CI

[!IMPORTANT] Viewing beta v1 documentation – usable but expect breaking changes. For stable version, see here

[!NOTE] Using React ⚛️ and tired of CSS-in-JS? See MistCSS 👀

Install

npm install json-server

Usage

Create a db.json or db.json5 file

{
  "$schema": "./node_modules/json-server/schema.json",
  "posts": [
    { "id": "1", "title": "a title", "views": 100 },
    { "id": "2", "title": "another title", "views": 200 }
  ],
  "comments": [
    { "id": "1", "text": "a comment about post 1", "postId": "1" },
    { "id": "2", "text": "another comment about post 1", "postId": "1" }
  ],
  "profile": {
    "name": "typicode"
  }
}
View db.json5 example
{
  posts: [
    { id: "1", title: "a title", views: 100 },
    { id: "2", title: "another title", views: 200 },
  ],
  comments: [
    { id: "1", text: "a comment about post 1", postId: "1" },
    { id: "2", text: "another comment about post 1", postId: "1" },
  ],
  profile: {
    name: "typicode",
  },
}

You can read more about JSON5 format here.

Start JSON Server

npx json-server db.json

This starts the server at http://localhost:3000. You should see:

JSON Server started on PORT :3000
http://localhost:3000

Access your REST API:

curl http://localhost:3000/posts/1

Response:

{
  "id": "1",
  "title": "a title",
  "views": 100
}

Run json-server --help for a list of options

Sponsors ✨

Gold

tower-dock-icon-light

Silver

Bronze

Become a sponsor and have your company logo here

Query Capabilities

JSON Server supports advanced querying out of the box:

GET /posts?views:gt=100                  # Filter by condition
GET /posts?_sort=-views                  # Sort by field (descending)
GET /posts?_page=1&_per_page=10          # Pagination
GET /posts?_embed=comments               # Include relations
GET /posts?_where={"or":[...]}           # Complex queries

See detailed documentation below for each feature.

Routes

Array Resources

For array resources like posts and comments:

GET    /posts
GET    /posts/:id
POST   /posts
PUT    /posts/:id
PATCH  /posts/:id
DELETE /posts/:id

Object Resources

For singular object resources like profile:

GET   /profile
PUT   /profile
PATCH /profile

Query params

Conditions

Use field:operator=value.

Operators:

  • no operator -> eq (equal)
  • lt less than, lte less than or equal
  • gt greater than, gte greater than or equal
  • eq equal, ne not equal
  • in included in comma-separated list
  • contains string contains (case-insensitive)
  • startsWith string starts with (case-insensitive)
  • endsWith string ends with (case-insensitive)

Examples:

GET /posts?views:gt=100
GET /posts?title:eq=Hello
GET /posts?id:in=1,2,3
GET /posts?author.name:eq=typicode
GET /posts?title:contains=hello
GET /posts?title:startsWith=Hello
GET /posts?title:endsWith=world

Sort

GET /posts?_sort=title
GET /posts?_sort=-views
GET /posts?_sort=author.name,-views

Pagination

GET /posts?_page=1&_per_page=25

Response:

{
  "first": 1,
  "prev": null,
  "next": 2,
  "last": 4,
  "pages": 4,
  "items": 100,
  "data": [
    { "id": "1", "title": "...", "views": 100 },
    { "id": "2", "title": "...", "views": 200 }
  ]
}

Notes:

  • _per_page defaults to 10 if not specified
  • Invalid _page or _per_page values are automatically normalized to valid ranges

Embed

GET /posts?_embed=comments
GET /comments?_embed=post

Complex filter with _where

_where accepts a JSON object and overrides normal query params when valid.

GET /posts?_where={"or":[{"views":{"gt":100}},{"author":{"name":{"lt":"m"}}}]}

Delete dependents

DELETE /posts/1?_dependent=comments

Static Files

JSON Server automatically serves files from the ./public directory.

To serve additional static directories:

json-server db.json -s ./static
json-server db.json -s ./static -s ./node_modules

Static files are served with standard MIME types and can include HTML, CSS, JavaScript, images, and other assets.

Migration Notes (v0 → v1)

If you are upgrading from json-server v0.x, note these behavioral changes:

  • ID handling: id is always a string and will be auto-generated if not provided
  • Pagination: Use _per_page with _page instead of the deprecated _limit parameter
  • Relationships: Use _embed instead of _expand for including related resources
  • Request delays: Use browser DevTools (Network tab > throttling) instead of the removed --delay CLI option

New to json-server? These notes are for users migrating from v0. If this is your first time using json-server, you can ignore this section.

NPM DownloadsLast 30 Days