json-server

Get a full fake REST API with zero coding in less than 30 seconds (seriousl...

README

JSON Server Node.js CI


Get a full fake REST API with __zero coding__ in __less than 30 seconds__ (seriously)

Created with <3 for front-end developers who need a quick back-end for prototyping and mocking.


See also:

 

Gold sponsors 🥇

 

 

 

 

 

Silver sponsors 🥈

 

 

 



Sponsor


__Please help me build OSS__ 👉 GitHub Sponsors :heart:

Table of contents


  Filter
  Sort
  Slice
  HTTPS
  Module
    + Simple example
    + API
  Video

Getting started


Install JSON Server

  1. ```
  2. npm install -g json-server
  3. ```

Create a db.json file with some data

  1. ``` json
  2. {
  3.   "posts": [
  4.     { "id": 1, "title": "json-server", "author": "typicode" }
  5.   ],
  6.   "comments": [
  7.     { "id": 1, "body": "some comment", "postId": 1 }
  8.   ],
  9.   "profile": { "name": "typicode" }
  10. }
  11. ```

Start JSON Server

  1. ``` sh
  2. json-server --watch db.json
  3. ```

Now if you go to http://localhost:3000/posts/1, you'll get

  1. ``` json
  2. { "id": 1, "title": "json-server", "author": "typicode" }
  3. ```

Also when doing requests, it's good to know that:

- If you make POST, PUT, PATCH or DELETE requests, changes will be automatically and safely saved to db.json using lowdb.
- Your request body JSON should be object enclosed, just like the GET output. (for example {"name": "Foobar"})
- Id values are not mutable. Any id value in the body of your PUT or PATCH request will be ignored. Only a value set in a POST request will be respected, but only if not already taken.
- A POST, PUT or PATCH request should include a Content-Type: application/json header to use the JSON in the request body. Otherwise it will return a 2XX status code, but without changes being made to the data.

Routes


Based on the previous db.json file, here are all the default routes. You can also add other routes using--routes.

Plural routes


  1. ```
  2. GET    /posts
  3. GET    /posts/1
  4. POST   /posts
  5. PUT    /posts/1
  6. PATCH  /posts/1
  7. DELETE /posts/1
  8. ```

Singular routes


  1. ```
  2. GET    /profile
  3. POST   /profile
  4. PUT    /profile
  5. PATCH  /profile
  6. ```

Filter


Use . to access deep properties

  1. ```
  2. GET /posts?title=json-server&author=typicode
  3. GET /posts?id=1&id=2
  4. GET /comments?author.name=typicode
  5. ```

Paginate


Use _page and optionally _limit to paginate returned data.

In the Link header you'll get first, prev, next and last links.

  1. ```
  2. GET /posts?_page=7
  3. GET /posts?_page=7&_limit=20
  4. ```

_10 items are returned by default_

Sort


Add _sort and _order (ascending order by default)

  1. ```
  2. GET /posts?_sort=views&_order=asc
  3. GET /posts/1/comments?_sort=votes&_order=asc
  4. ```

For multiple fields, use the following format:

  1. ```
  2. GET /posts?_sort=user,views&_order=desc,asc
  3. ```

Slice


Add _start and _end or _limit (an X-Total-Count header is included in the response)

  1. ```
  2. GET /posts?_start=20&_end=30
  3. GET /posts/1/comments?_start=20&_end=30
  4. GET /posts/1/comments?_start=20&_limit=10
  5. ```

_Works exactly as Array.slice (i.e._start is inclusive and _end exclusive)_

Operators


Add _gte or _lte for getting a range

  1. ```
  2. GET /posts?views_gte=10&views_lte=20
  3. ```

Add _ne to exclude a value

  1. ```
  2. GET /posts?id_ne=1
  3. ```

Add _like to filter (RegExp supported)

  1. ```
  2. GET /posts?title_like=server
  3. ```

Full-text search


Add q

  1. ```
  2. GET /posts?q=internet
  3. ```

Relationships


To include children resources, add _embed

  1. ```
  2. GET /posts?_embed=comments
  3. GET /posts/1?_embed=comments
  4. ```

To include parent resource, add _expand

  1. ```
  2. GET /comments?_expand=post
  3. GET /comments/1?_expand=post
  4. ```

To get or create nested resources (by default one level, add custom routes for more)

  1. ```
  2. GET  /posts/1/comments
  3. POST /posts/1/comments
  4. ```

Database


  1. ```
  2. GET /db
  3. ```

Homepage


Returns default index file or serves ./public directory

  1. ```
  2. GET /
  3. ```

Extras


Static file server


You can use JSON Server to serve your HTML, JS and CSS, simply create a ./public directory
or use --static to set a different static files directory.

  1. ``` sh
  2. mkdir public
  3. echo 'hello world' > public/index.html
  4. json-server db.json
  5. ```

  1. ``` sh
  2. json-server db.json --static ./some-other-dir
  3. ```

Alternative port


You can start JSON Server on other ports with the --port flag:

  1. ``` sh
  2. $ json-server --watch db.json --port 3004
  3. ```

Access from anywhere


You can access your fake API from anywhere using CORS and JSONP.

Remote schema


You can load remote schemas.

  1. ``` sh
  2. $ json-server http://example.com/file.json
  3. $ json-server http://jsonplaceholder.typicode.com/db
  4. ```

Generate random data


Using JS instead of a JSON file, you can create data programmatically.

  1. ``` js
  2. // index.js
  3. module.exports = () => {
  4.   const data = { users: [] }
  5.   // Create 1000 users
  6.   for (let i = 0; i < 1000; i++) {
  7.     data.users.push({ id: i, name: `user${i}` })
  8.   }
  9.   return data
  10. }
  11. ```

  1. ``` sh
  2. $ json-server index.js
  3. ```

__Tip__ use modules like Faker, Casual, Chance or JSON Schema Faker.

HTTPS


There are many ways to set up SSL in development. One simple way is to use hotel.

Add custom routes


Create a routes.json file. Pay attention to start every route with /.

  1. ``` json
  2. {
  3.   "/api/*": "/$1",
  4.   "/:resource/:id/show": "/:resource/:id",
  5.   "/posts/:category": "/posts?category=:category",
  6.   "/articles\\?id=:id": "/posts/:id"
  7. }
  8. ```

Start JSON Server with --routes option.

  1. ``` sh
  2. json-server db.json --routes routes.json
  3. ```

Now you can access resources using additional routes.

  1. ```sh
  2. /api/posts # /posts
  3. /api/posts/1  # → /posts/1
  4. /posts/1/show # → /posts/1
  5. /posts/javascript # /posts?category=javascript
  6. /articles?id=1 # → /posts/1
  7. ```

Add middlewares


You can add your middlewares from the CLI using --middlewares option:

  1. ``` js
  2. // hello.js
  3. module.exports = (req, res, next) => {
  4.   res.header('X-Hello', 'World')
  5.   next()
  6. }
  7. ```

  1. ``` sh
  2. json-server db.json --middlewares ./hello.js
  3. json-server db.json --middlewares ./first.js ./second.js
  4. ```

CLI usage


  1. ```
  2. json-server [options] <source>

  3. Options:
  4.   --config, -c       Path to config file           [default: "json-server.json"]
  5.   --port, -p         Set port                                    [default: 3000]
  6.   --host, -H         Set host                             [default: "localhost"]
  7.   --watch, -w        Watch file(s)                                     [boolean]
  8.   --routes, -r       Path to routes file
  9.   --middlewares, -m  Paths to middleware files                           [array]
  10.   --static, -s       Set static files directory
  11.   --read-only, --ro  Allow only GET requests                           [boolean]
  12.   --no-cors, --nc    Disable Cross-Origin Resource Sharing             [boolean]
  13.   --no-gzip, --ng    Disable GZIP Content-Encoding                     [boolean]
  14.   --snapshots, -S    Set snapshots directory                      [default: "."]
  15.   --delay, -d        Add delay to responses (ms)
  16.   --id, -i           Set database id property (e.g. _id)         [default: "id"]
  17.   --foreignKeySuffix, --fks  Set foreign key suffix, (e.g. _id as in post_id)
  18.                                                                  [default: "Id"]
  19.   --quiet, -q        Suppress log messages from output                 [boolean]
  20.   --help, -h         Show help                                         [boolean]
  21.   --version, -v      Show version number                               [boolean]

  22. Examples:
  23.   json-server db.json
  24.   json-server file.js
  25.   json-server http://example.com/db.json

  26. https://github.com/typicode/json-server
  27. ```

You can also set options in a json-server.json configuration file.

  1. ``` json
  2. {
  3.   "port": 3000
  4. }
  5. ```

Module


If you need to add authentication, validation, or __any behavior__, you can use the project as a module in combination with other Express middlewares.

Simple example


  1. ```sh
  2. $ npm install json-server --save-dev
  3. ```

  1. ``` js
  2. // server.js
  3. const jsonServer = require('json-server')
  4. const server = jsonServer.create()
  5. const router = jsonServer.router('db.json')
  6. const middlewares = jsonServer.defaults()

  7. server.use(middlewares)
  8. server.use(router)
  9. server.listen(3000, () => {
  10.   console.log('JSON Server is running')
  11. })
  12. ```

  1. ```sh
  2. $ node server.js
  3. ```

The path you provide to the jsonServer.router function  is relative to the directory from where you launch your node process. If you run the above code from another directory, it’s better to use an absolute path:

  1. ``` js
  2. const path = require('path')
  3. const router = jsonServer.router(path.join(__dirname, 'db.json'))
  4. ```

For an in-memory database, simply pass an object to jsonServer.router().

To add custom options (eg. foreginKeySuffix) pass in an object as the second argument to jsonServer.router('db.json', { foreginKeySuffix: '_id' }).

Please note also that jsonServer.router() can be used in existing Express projects.

Custom routes example


Let's say you want a route that echoes query parameters and another one that set a timestamp on every resource created.

  1. ``` js
  2. const jsonServer = require('json-server')
  3. const server = jsonServer.create()
  4. const router = jsonServer.router('db.json')
  5. const middlewares = jsonServer.defaults()

  6. // Set default middlewares (logger, static, cors and no-cache)
  7. server.use(middlewares)

  8. // Add custom routes before JSON Server router
  9. server.get('/echo', (req, res) => {
  10.   res.jsonp(req.query)
  11. })

  12. // To handle POST, PUT and PATCH you need to use a body-parser
  13. // You can use the one used by JSON Server
  14. server.use(jsonServer.bodyParser)
  15. server.use((req, res, next) => {
  16.   if (req.method === 'POST') {
  17.     req.body.createdAt = Date.now()
  18.   }
  19.   // Continue to JSON Server router
  20.   next()
  21. })

  22. // Use default router
  23. server.use(router)
  24. server.listen(3000, () => {
  25.   console.log('JSON Server is running')
  26. })
  27. ```

Access control example


  1. ``` js
  2. const jsonServer = require('json-server')
  3. const server = jsonServer.create()
  4. const router = jsonServer.router('db.json')
  5. const middlewares = jsonServer.defaults()

  6. server.use(middlewares)
  7. server.use((req, res, next) => {
  8. if (isAuthorized(req)) { // add your authorization logic here
  9.    next() // continue to JSON Server router
  10. } else {
  11.    res.sendStatus(401)
  12. }
  13. })
  14. server.use(router)
  15. server.listen(3000, () => {
  16.   console.log('JSON Server is running')
  17. })
  18. ```

Custom output example


To modify responses, overwrite router.render method:

  1. ``` js
  2. // In this example, returned resources will be wrapped in a body property
  3. router.render = (req, res) => {
  4.   res.jsonp({
  5.     body: res.locals.data
  6.   })
  7. }
  8. ```

You can set your own status code for the response:

  1. ``` js
  2. // In this example we simulate a server side error response
  3. router.render = (req, res) => {
  4.   res.status(500).jsonp({
  5.     error: "error message here"
  6.   })
  7. }
  8. ```

Rewriter example


To add rewrite rules, use jsonServer.rewriter():

  1. ``` js
  2. // Add this before server.use(router)
  3. server.use(jsonServer.rewriter({
  4.   '/api/*': '/$1',
  5.   '/blog/:resource/:id/show': '/:resource/:id'
  6. }))
  7. ```

Mounting JSON Server on another endpoint example


Alternatively, you can also mount the router on /api.

  1. ``` js
  2. server.use('/api', router)
  3. ```

API


__jsonServer.create()__

Returns an Express server.

__jsonServer.defaults([options])__

Returns middlewares used by JSON Server.

options
  static path to static files
  logger enable logger middleware (default: true)
  bodyParser enable body-parser middleware (default: true)
  noCors disable CORS (default: false)
  readOnly accept only GET requests (default: false)

__jsonServer.router([path|object], [options])__

Returns JSON Server router.

options (see CLI usage)

Deployment


You can deploy JSON Server. For example, JSONPlaceholder is an online fake API powered by JSON Server and running on Heroku.

Links


Video



Articles



Third-party tools



License


MIT