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)

72,757
7,009
72,757
700

Top Related Projects

6,354

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

12,708

HTTP server mocking and expectations library for Node.js

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

15,796

Seamless REST/GraphQL API mocking library for browser and Node.js.

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

6,354

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"
    }
  ]
12,708

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.

15,796

Seamless REST/GraphQL API mocking library for browser and Node.js.

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

👋 Hey! Using React, Vue or Astro? Check my new project MistCSS to write 50% less code.

Install

npm install json-server

Usage

Create a db.json or db.json5 file

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

Pass it to JSON Server CLI

$ npx json-server db.json

Get a REST API

$ curl http://localhost:3000/posts/1
{
  "id": "1",
  "title": "a title",
  "views": 100
}

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

Sponsors ✨

Sponsors
Sponsors
Sponsors
Delivery Routing Software and Route Optimization Software

Become a sponsor and have your company logo here

Sponsorware

[!NOTE] This project uses the Fair Source License. Only organizations with 3+ users are kindly asked to contribute a small amount through sponsorship sponsor for usage. This license helps keep the project sustainable and healthy, benefiting everyone.

For more information, FAQs, and the rationale behind this, visit https://fair.io/.

Routes

Based on the example db.json, you'll get the following routes:

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

# Same for comments
GET   /profile
PUT   /profile
PATCH /profile

Params

Conditions

  • → ==
  • lt → <
  • lte → <=
  • gt → >
  • gte → >=
  • ne → !=
GET /posts?views_gt=9000

Range

  • start
  • end
  • limit
GET /posts?_start=10&_end=20
GET /posts?_start=10&_limit=10

Paginate

  • page
  • per_page (default = 10)
GET /posts?_page=1&_per_page=25

Sort

  • _sort=f1,f2
GET /posts?_sort=id,-views

Nested and array fields

  • x.y.z...
  • x.y.z[i]...
GET /foo?a.b=bar
GET /foo?x.y_lt=100
GET /foo?arr[0]=bar

Embed

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

Delete

DELETE /posts/1
DELETE /posts/1?_dependent=comments

Serving static files

If you create a ./public directory, JSON Server will serve its content in addition to the REST API.

You can also add custom directories using -s/--static option.

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

Notable differences with v0.17

  • id is always a string and will be generated for you if missing
  • use _per_page with _page instead of _limitfor pagination
  • use Chrome's Network tab > throtling to delay requests instead of --delay CLI option

NPM DownloadsLast 30 Days