json-server 0.17.3 → 1.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,649 +1,112 @@
1
- # JSON Server [![Node.js CI](https://github.com/typicode/json-server/actions/workflows/node.js.yml/badge.svg?branch=master)](https://github.com/typicode/json-server/actions/workflows/node.js.yml)
1
+ # json-server
2
2
 
3
- Get a full fake REST API with __zero coding__ in __less than 30 seconds__ (seriously)
3
+ [![Node.js CI](https://github.com/typicode/json-server/actions/workflows/node.js.yml/badge.svg)](https://github.com/typicode/json-server/actions/workflows/node.js.yml)
4
4
 
5
- Created with <3 for front-end developers who need a quick back-end for prototyping and mocking.
5
+ ## Usage
6
6
 
7
- * [Egghead.io free video tutorial - Creating demo APIs with json-server](https://egghead.io/lessons/nodejs-creating-demo-apis-with-json-server)
8
- * [JSONPlaceholder - Live running version](https://jsonplaceholder.typicode.com)
9
- * [__My JSON Server__ - no installation required, use your own data](https://my-json-server.typicode.com)
7
+ Install `json-server`
10
8
 
11
- See also:
12
- * :dog: [husky - Git hooks made easy](https://github.com/typicode/husky)
13
- * :owl: [lowdb - local JSON database](https://github.com/typicode/lowdb)
14
- * ✅ [xv - a beautifully simple and capable test runner](https://github.com/typicode/xv)
15
-
16
- <p>&nbsp;</p>
17
-
18
- <h2 align="center">Gold sponsors 🥇</h2>
19
-
20
- <p>&nbsp;</p>
21
-
22
- <p align="center">
23
- <a href="https://tryretool.com/?utm_source=sponsor&utm_campaign=typicode" target="_blank">
24
- <img src="https://i.imgur.com/IBItATn.png" height="70px">
25
- </a>
26
- </p>
27
-
28
- <p>&nbsp;</p>
29
-
30
- <p align="center">
31
- <a href="https://mockend.com/" target="_blank">
32
- <img src="https://jsonplaceholder.typicode.com/mockend.svg" height="70px">
33
- </a>
34
- </p>
35
-
36
- <p>&nbsp;</p>
37
-
38
- <p align="center">
39
- <a href="https://megafamous.com/buy-instagram-followers" target="_blank">
40
- <img src="https://jsonplaceholder.typicode.com/megafamous.png" height="70px">
41
- </a>
42
- </p>
43
-
44
- <p>&nbsp;</p>
45
-
46
- <p align="center">
47
- <a href="http://asocks.com/c/TFw5bz" target="_blank">
48
- <img src="https://jsonplaceholder.typicode.com/asocks.png" height="70px">
49
- </a>
50
- </p>
51
-
52
- <p>&nbsp;</p>
53
-
54
- <p>&nbsp;</p>
55
-
56
- <h2 align="center">Silver sponsors 🥈</h2>
57
-
58
- <p>&nbsp;</p>
59
-
60
- <p align="center">
61
- <a href="https://cased.com" target="_blank">
62
- <img src="https://user-images.githubusercontent.com/5502029/194441951-b7dca49d-efd6-496d-900b-288004717f11.png" height="55px">
63
- </a>
64
- </p>
65
-
66
- <p>&nbsp;</p>
67
-
68
- <p>&nbsp;</p>
69
-
70
- [Become a sponsor and have your company logo here](https://github.com/users/typicode/sponsorship)
71
-
72
- ## Sponsor
73
-
74
- __Please help me build OSS__ 👉 [GitHub Sponsors](https://github.com/sponsors/typicode) :heart:
75
-
76
- ## Table of contents
77
-
78
- <!-- toc -->
79
-
80
- - [Getting started](#getting-started)
81
- - [Routes](#routes)
82
- * [Plural routes](#plural-routes)
83
- * [Singular routes](#singular-routes)
84
- * [Filter](#filter)
85
- * [Paginate](#paginate)
86
- * [Sort](#sort)
87
- * [Slice](#slice)
88
- * [Operators](#operators)
89
- * [Full-text search](#full-text-search)
90
- * [Relationships](#relationships)
91
- * [Database](#database)
92
- * [Homepage](#homepage)
93
- - [Extras](#extras)
94
- * [Static file server](#static-file-server)
95
- * [Alternative port](#alternative-port)
96
- * [Access from anywhere](#access-from-anywhere)
97
- * [Remote schema](#remote-schema)
98
- * [Generate random data](#generate-random-data)
99
- * [HTTPS](#https)
100
- * [Add custom routes](#add-custom-routes)
101
- * [Add middlewares](#add-middlewares)
102
- * [CLI usage](#cli-usage)
103
- * [Module](#module)
104
- + [Simple example](#simple-example)
105
- + [Custom routes example](#custom-routes-example)
106
- + [Access control example](#access-control-example)
107
- + [Custom output example](#custom-output-example)
108
- + [Rewriter example](#rewriter-example)
109
- + [Mounting JSON Server on another endpoint example](#mounting-json-server-on-another-endpoint-example)
110
- + [API](#api)
111
- * [Deployment](#deployment)
112
- - [Links](#links)
113
- * [Video](#video)
114
- * [Articles](#articles)
115
- * [Third-party tools](#third-party-tools)
116
- - [License](#license)
117
-
118
- <!-- tocstop -->
119
-
120
- ## Getting started
121
-
122
- Install JSON Server
123
-
124
- ```
125
- npm install -g json-server
9
+ ```shell
10
+ npm install json-server
126
11
  ```
127
12
 
128
- Create a `db.json` file with some data
13
+ Create a `db.json` file or run `json-server db.json` to create one with some default resources
129
14
 
130
15
  ```json
131
16
  {
132
17
  "posts": [
133
- { "id": 1, "title": "json-server", "author": "typicode" }
18
+ { "id": "1", "title": "string" },
19
+ { "id": "2", "title": "some post" }
134
20
  ],
135
21
  "comments": [
136
- { "id": 1, "body": "some comment", "postId": 1 }
137
- ],
138
- "profile": { "name": "typicode" }
22
+ { "id": "1", "text": "some text", "postId": "1" },
23
+ { "id": "2", "text": "some text", "postId": "1" }
24
+ ]
139
25
  }
140
26
  ```
141
27
 
142
- Start JSON Server
143
-
144
- ```bash
145
- json-server --watch db.json
146
- ```
147
-
148
- Now if you go to [http://localhost:3000/posts/1](http://localhost:3000/posts/1), you'll get
149
-
150
- ```json
151
- { "id": 1, "title": "json-server", "author": "typicode" }
28
+ ```shell
29
+ json-server db.json
152
30
  ```
153
31
 
154
- Also when doing requests, it's good to know that:
155
-
156
- - If you make POST, PUT, PATCH or DELETE requests, changes will be automatically and safely saved to `db.json` using [lowdb](https://github.com/typicode/lowdb).
157
- - Your request body JSON should be object enclosed, just like the GET output. (for example `{"name": "Foobar"}`)
158
- - 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.
159
- - 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.
32
+ Run `json-server --help` for a list of options
160
33
 
161
34
  ## Routes
162
35
 
163
- Based on the previous `db.json` file, here are all the default routes. You can also add [other routes](#add-custom-routes) using `--routes`.
164
-
165
- ### Plural routes
166
-
167
36
  ```
168
37
  GET /posts
169
- GET /posts/1
38
+ GET /posts/:id
170
39
  POST /posts
171
- PUT /posts/1
172
- PATCH /posts/1
173
- DELETE /posts/1
174
- ```
175
-
176
- ### Singular routes
177
-
178
- ```
179
- GET /profile
180
- POST /profile
181
- PUT /profile
182
- PATCH /profile
183
- ```
184
-
185
- ### Filter
186
-
187
- Use `.` to access deep properties
188
-
189
- ```
190
- GET /posts?title=json-server&author=typicode
191
- GET /posts?id=1&id=2
192
- GET /comments?author.name=typicode
193
- ```
194
-
195
- ### Paginate
196
-
197
- Use `_page` and optionally `_limit` to paginate returned data.
198
-
199
- In the `Link` header you'll get `first`, `prev`, `next` and `last` links.
200
-
201
-
202
- ```
203
- GET /posts?_page=7
204
- GET /posts?_page=7&_limit=20
205
- ```
206
-
207
- _10 items are returned by default_
208
-
209
- ### Sort
210
-
211
- Add `_sort` and `_order` (ascending order by default)
212
-
213
- ```
214
- GET /posts?_sort=views&_order=asc
215
- GET /posts/1/comments?_sort=votes&_order=asc
216
- ```
217
-
218
- For multiple fields, use the following format:
219
-
220
- ```
221
- GET /posts?_sort=user,views&_order=desc,asc
222
- ```
223
-
224
- ### Slice
225
-
226
- Add `_start` and `_end` or `_limit` (an `X-Total-Count` header is included in the response)
227
-
228
- ```
229
- GET /posts?_start=20&_end=30
230
- GET /posts/1/comments?_start=20&_end=30
231
- GET /posts/1/comments?_start=20&_limit=10
232
- ```
233
-
234
- _Works exactly as [Array.slice](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) (i.e. `_start` is inclusive and `_end` exclusive)_
235
-
236
- ### Operators
237
-
238
- Add `_gte` or `_lte` for getting a range
239
-
240
- ```
241
- GET /posts?views_gte=10&views_lte=20
242
- ```
243
-
244
- Add `_ne` to exclude a value
245
-
246
- ```
247
- GET /posts?id_ne=1
248
- ```
249
-
250
- Add `_like` to filter (RegExp supported)
251
-
252
- ```
253
- GET /posts?title_like=server
254
- ```
255
-
256
- ### Full-text search
257
-
258
- Add `q`
259
-
260
- ```
261
- GET /posts?q=internet
262
- ```
263
-
264
- ### Relationships
265
-
266
- To include children resources, add `_embed`
267
-
268
- ```
269
- GET /posts?_embed=comments
270
- GET /posts/1?_embed=comments
271
- ```
272
-
273
- To include parent resource, add `_expand`
274
-
275
- ```
276
- GET /comments?_expand=post
277
- GET /comments/1?_expand=post
278
- ```
279
-
280
- To get or create nested resources (by default one level, [add custom routes](#add-custom-routes) for more)
281
-
282
- ```
283
- GET /posts/1/comments
284
- POST /posts/1/comments
40
+ PUT /posts
41
+ DELETE /posts/:id
285
42
  ```
286
43
 
287
- ### Database
44
+ ## Params
288
45
 
289
- ```
290
- GET /db
291
- ```
46
+ ### Comparison
292
47
 
293
- ### Homepage
294
-
295
- Returns default index file or serves `./public` directory
48
+ - ` ` →`==`
49
+ - `lt` → `<`
50
+ - `lte` `<=`
51
+ - `gt` → `>`
52
+ - `gte` → `>=`
53
+ - `ne` → `!=`
296
54
 
297
55
  ```
298
- GET /
56
+ GET /posts?views_gt=9000
299
57
  ```
300
58
 
301
- ## Extras
302
-
303
- ### Static file server
59
+ ### Range
304
60
 
305
- You can use JSON Server to serve your HTML, JS and CSS, simply create a `./public` directory
306
- or use `--static` to set a different static files directory.
61
+ - `start`
62
+ - `end`
63
+ - `limit`
307
64
 
308
- ```bash
309
- mkdir public
310
- echo 'hello world' > public/index.html
311
- json-server db.json
312
65
  ```
313
-
314
- ```bash
315
- json-server db.json --static ./some-other-dir
66
+ GET /posts?_start=10&_end=20
67
+ GET /posts?_start=10&_limit=10
316
68
  ```
317
69
 
318
- ### Alternative port
319
-
320
- You can start JSON Server on other ports with the `--port` flag:
321
-
322
- ```bash
323
- $ json-server --watch db.json --port 3004
324
- ```
325
-
326
- ### Access from anywhere
327
-
328
- You can access your fake API from anywhere using CORS and JSONP.
329
-
330
- ### Remote schema
331
-
332
- You can load remote schemas.
333
-
334
- ```bash
335
- $ json-server http://example.com/file.json
336
- $ json-server http://jsonplaceholder.typicode.com/db
337
- ```
338
-
339
- ### Generate random data
70
+ ### Paginate
340
71
 
341
- Using JS instead of a JSON file, you can create data programmatically.
72
+ - `page`
73
+ - `per_page` (default = 10)
342
74
 
343
- ```javascript
344
- // index.js
345
- module.exports = () => {
346
- const data = { users: [] }
347
- // Create 1000 users
348
- for (let i = 0; i < 1000; i++) {
349
- data.users.push({ id: i, name: `user${i}` })
350
- }
351
- return data
352
- }
353
75
  ```
354
-
355
- ```bash
356
- $ json-server index.js
76
+ GET /posts?_page=1&_per_page=25
357
77
  ```
358
78
 
359
- __Tip__ use modules like [Faker](https://github.com/faker-js/faker), [Casual](https://github.com/boo1ean/casual), [Chance](https://github.com/victorquinn/chancejs) or [JSON Schema Faker](https://github.com/json-schema-faker/json-schema-faker).
360
-
361
- ### HTTPS
362
-
363
- There are many ways to set up SSL in development. One simple way is to use [hotel](https://github.com/typicode/hotel).
364
-
365
- ### Add custom routes
79
+ ### Sort
366
80
 
367
- Create a `routes.json` file. Pay attention to start every route with `/`.
81
+ - `_sort=f1,f2`
368
82
 
369
- ```json
370
- {
371
- "/api/*": "/$1",
372
- "/:resource/:id/show": "/:resource/:id",
373
- "/posts/:category": "/posts?category=:category",
374
- "/articles\\?id=:id": "/posts/:id"
375
- }
376
83
  ```
377
-
378
- Start JSON Server with `--routes` option.
379
-
380
- ```bash
381
- json-server db.json --routes routes.json
84
+ GET /posts?_sort=id,-views
382
85
  ```
383
86
 
384
- Now you can access resources using additional routes.
87
+ ### Nested fields
385
88
 
386
- ```sh
387
- /api/posts # → /posts
388
- /api/posts/1 # → /posts/1
389
- /posts/1/show # → /posts/1
390
- /posts/javascript # → /posts?category=javascript
391
- /articles?id=1 # → /posts/1
392
- ```
393
-
394
- ### Add middlewares
89
+ - `x.y.z`
395
90
 
396
- You can add your middlewares from the CLI using `--middlewares` option:
91
+ ### Include
397
92
 
398
- ```js
399
- // hello.js
400
- module.exports = (req, res, next) => {
401
- res.header('X-Hello', 'World')
402
- next()
403
- }
404
93
  ```
405
-
406
- ```bash
407
- json-server db.json --middlewares ./hello.js
408
- json-server db.json --middlewares ./first.js ./second.js
94
+ GET /posts?_include=comments
95
+ GET /comments?_include=post
409
96
  ```
410
97
 
411
- ### CLI usage
98
+ ## Delete
412
99
 
413
100
  ```
414
- json-server [options] <source>
415
-
416
- Options:
417
- --config, -c Path to config file [default: "json-server.json"]
418
- --port, -p Set port [default: 3000]
419
- --host, -H Set host [default: "localhost"]
420
- --watch, -w Watch file(s) [boolean]
421
- --routes, -r Path to routes file
422
- --middlewares, -m Paths to middleware files [array]
423
- --static, -s Set static files directory
424
- --read-only, --ro Allow only GET requests [boolean]
425
- --no-cors, --nc Disable Cross-Origin Resource Sharing [boolean]
426
- --no-gzip, --ng Disable GZIP Content-Encoding [boolean]
427
- --snapshots, -S Set snapshots directory [default: "."]
428
- --delay, -d Add delay to responses (ms)
429
- --id, -i Set database id property (e.g. _id) [default: "id"]
430
- --foreignKeySuffix, --fks Set foreign key suffix, (e.g. _id as in post_id)
431
- [default: "Id"]
432
- --quiet, -q Suppress log messages from output [boolean]
433
- --help, -h Show help [boolean]
434
- --version, -v Show version number [boolean]
435
-
436
- Examples:
437
- json-server db.json
438
- json-server file.js
439
- json-server http://example.com/db.json
440
-
441
- https://github.com/typicode/json-server
442
- ```
443
-
444
- You can also set options in a `json-server.json` configuration file.
445
-
446
- ```json
447
- {
448
- "port": 3000
449
- }
101
+ DELETE /posts/1
102
+ DELETE /posts/1?_include=comments
450
103
  ```
451
104
 
452
- ### Module
453
-
454
- If you need to add authentication, validation, or __any behavior__, you can use the project as a module in combination with other Express middlewares.
455
-
456
- #### Simple example
457
-
458
- ```sh
459
- $ npm install json-server --save-dev
460
- ```
105
+ # Serving static files
461
106
 
462
- ```js
463
- // server.js
464
- const jsonServer = require('json-server')
465
- const server = jsonServer.create()
466
- const router = jsonServer.router('db.json')
467
- const middlewares = jsonServer.defaults()
468
-
469
- server.use(middlewares)
470
- server.use(router)
471
- server.listen(3000, () => {
472
- console.log('JSON Server is running')
473
- })
474
- ```
107
+ If you create a `./public` directory, JSON Serve will serve its content in addition to the REST API. You can add custom directories using `-s/--static` option.
475
108
 
476
109
  ```sh
477
- $ node server.js
478
- ```
479
-
480
- 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:
481
-
482
- ```js
483
- const path = require('path')
484
- const router = jsonServer.router(path.join(__dirname, 'db.json'))
485
- ```
486
-
487
- For an in-memory database, simply pass an object to `jsonServer.router()`.
488
-
489
- To add custom options (eg. `foreginKeySuffix`) pass in an object as the second argument to `jsonServer.router('db.json', { foreginKeySuffix: '_id' })`.
490
-
491
- Please note also that `jsonServer.router()` can be used in existing Express projects.
492
-
493
- #### Custom routes example
494
-
495
- Let's say you want a route that echoes query parameters and another one that set a timestamp on every resource created.
496
-
497
- ```js
498
- const jsonServer = require('json-server')
499
- const server = jsonServer.create()
500
- const router = jsonServer.router('db.json')
501
- const middlewares = jsonServer.defaults()
502
-
503
- // Set default middlewares (logger, static, cors and no-cache)
504
- server.use(middlewares)
505
-
506
- // Add custom routes before JSON Server router
507
- server.get('/echo', (req, res) => {
508
- res.jsonp(req.query)
509
- })
510
-
511
- // To handle POST, PUT and PATCH you need to use a body-parser
512
- // You can use the one used by JSON Server
513
- server.use(jsonServer.bodyParser)
514
- server.use((req, res, next) => {
515
- if (req.method === 'POST') {
516
- req.body.createdAt = Date.now()
517
- }
518
- // Continue to JSON Server router
519
- next()
520
- })
521
-
522
- // Use default router
523
- server.use(router)
524
- server.listen(3000, () => {
525
- console.log('JSON Server is running')
526
- })
527
- ```
528
-
529
- #### Access control example
530
-
531
- ```js
532
- const jsonServer = require('json-server')
533
- const server = jsonServer.create()
534
- const router = jsonServer.router('db.json')
535
- const middlewares = jsonServer.defaults()
536
-
537
- server.use(middlewares)
538
- server.use((req, res, next) => {
539
- if (isAuthorized(req)) { // add your authorization logic here
540
- next() // continue to JSON Server router
541
- } else {
542
- res.sendStatus(401)
543
- }
544
- })
545
- server.use(router)
546
- server.listen(3000, () => {
547
- console.log('JSON Server is running')
548
- })
549
- ```
550
- #### Custom output example
551
-
552
- To modify responses, overwrite `router.render` method:
553
-
554
- ```javascript
555
- // In this example, returned resources will be wrapped in a body property
556
- router.render = (req, res) => {
557
- res.jsonp({
558
- body: res.locals.data
559
- })
560
- }
561
- ```
562
-
563
- You can set your own status code for the response:
564
-
565
-
566
- ```javascript
567
- // In this example we simulate a server side error response
568
- router.render = (req, res) => {
569
- res.status(500).jsonp({
570
- error: "error message here"
571
- })
572
- }
573
- ```
574
-
575
- #### Rewriter example
576
-
577
- To add rewrite rules, use `jsonServer.rewriter()`:
578
-
579
- ```javascript
580
- // Add this before server.use(router)
581
- server.use(jsonServer.rewriter({
582
- '/api/*': '/$1',
583
- '/blog/:resource/:id/show': '/:resource/:id'
584
- }))
110
+ json-server -s ./static
111
+ json-server -s ./static -s ./node_modules
585
112
  ```
586
-
587
- #### Mounting JSON Server on another endpoint example
588
-
589
- Alternatively, you can also mount the router on `/api`.
590
-
591
- ```javascript
592
- server.use('/api', router)
593
- ```
594
-
595
- #### API
596
-
597
- __`jsonServer.create()`__
598
-
599
- Returns an Express server.
600
-
601
- __`jsonServer.defaults([options])`__
602
-
603
- Returns middlewares used by JSON Server.
604
-
605
- * options
606
- * `static` path to static files
607
- * `logger` enable logger middleware (default: true)
608
- * `bodyParser` enable body-parser middleware (default: true)
609
- * `noCors` disable CORS (default: false)
610
- * `readOnly` accept only GET requests (default: false)
611
-
612
- __`jsonServer.router([path|object], [options])`__
613
-
614
- Returns JSON Server router.
615
-
616
- * options (see [CLI usage](#cli-usage))
617
-
618
- ### Deployment
619
-
620
- You can deploy JSON Server. For example, [JSONPlaceholder](http://jsonplaceholder.typicode.com) is an online fake API powered by JSON Server and running on Heroku.
621
-
622
- ## Links
623
-
624
- ### Video
625
-
626
- * [Creating Demo APIs with json-server on egghead.io](https://egghead.io/lessons/nodejs-creating-demo-apis-with-json-server)
627
-
628
- ### Articles
629
-
630
- * [Node Module Of The Week - json-server](http://nmotw.in/json-server/)
631
- * [ng-admin: Add an AngularJS admin GUI to any RESTful API](http://marmelab.com/blog/2014/09/15/easy-backend-for-your-restful-api.html)
632
- * [Fast prototyping using Restangular and Json-server](https://glebbahmutov.com/blog/fast-prototyping-restangular-and-json-server/)
633
- * [Create a Mock REST API in Seconds for Prototyping your Frontend](https://coligo.io/create-mock-rest-api-with-json-server/)
634
- * [No API? No Problem! Rapid Development via Mock APIs](https://medium.com/@housecor/rapid-development-via-mock-apis-e559087be066#.93d7w8oro)
635
- * [Zero Code REST With json-server](https://dzone.com/articles/zero-code-rest-with-json-server)
636
-
637
- ### Third-party tools
638
-
639
- * [Grunt JSON Server](https://github.com/tfiwm/grunt-json-server)
640
- * [Docker JSON Server](https://github.com/clue/docker-json-server)
641
- * [JSON Server GUI](https://github.com/naholyr/json-server-gui)
642
- * [JSON file generator](https://github.com/dfsq/json-server-init)
643
- * [JSON Server extension](https://github.com/maty21/json-server-extension)
644
-
645
- ## License
646
-
647
- MIT
648
-
649
- [Supporters](https://thanks.typicode.com) ✨