Json Server Middle Ware for File Upload
JSON Server
Get a full fake REST API with nothing coding in less than 30 seconds (seriously)
Created with <iii for front-end developers who demand a quick dorsum-end for prototyping and mocking.
- Egghead.io gratuitous video tutorial - Creating demo APIs with json-server
- JSONPlaceholder - Live running version
- My JSON Server - no installation required, use your own data
Come across also:
-
🐶 croaking - Git hooks made easy -
🦉 lowdb - local JSON database -
❌ ✔️ xv - the virtually minimalist test runner
Gilt sponsors 🥇
From generating an API to importing a CSV into postgres, Retool's range of 20+ developer utilities is a become-to resource when building apps. Check it out at present
Go a sponsor and have your company logo here
Sponsor
Please help me build OSS
Table of contents
- Getting started
- Routes
- Plural routes
- Atypical routes
- Filter
- Paginate
- Sort
- Slice
- Operators
- Full-text search
- Relationships
- Database
- Homepage
- Extras
- Static file server
- Alternative port
- Access from anywhere
- Remote schema
- Generate random information
- HTTPS
- Add custom routes
- Add middlewares
- CLI usage
- Module
- Simple example
- Custom routes example
- Access control case
- Custom output instance
- Rewriter example
- Mounting JSON Server on another endpoint instance
- API
- Deployment
- Links
- Video
- Articles
- Third-party tools
- License
Getting started
Install JSON Server
npm install -g json-server
Create a db.json
file with some data
{ "posts" : [ { "id" : ane, "championship" : "json-server" , "author" : "typicode" } ], "comments" : [ { "id" : 1, "body" : "some comment" , "postId" : one } ], "profile" : { "name" : "typicode" } }
Starting time JSON Server
json-server --watch db.json
At present if you become to http://localhost:3000/posts/ane, you'll go
{ "id" : 1, "title" : "json-server" , "author" : "typicode" }
Also when doing requests, it's proficient to know that:
- If you lot make POST, PUT, PATCH or DELETE requests, changes will be automatically and safely saved to
db.json
using lowdb. - Your asking body JSON should exist object enclosed, just like the Become output. (for example
{"name": "Foobar"}
) - Id values are not mutable. Any
id
value in the trunk of your PUT or PATCH request volition be ignored. Merely a value gear up in a POST asking volition be respected, simply only if not already taken. - A POST, PUT or PATCH request should include a
Content-Type: application/json
header to employ the JSON in the request body. Otherwise information technology will return a 2XX condition lawmaking, but without changes beingness made to the data.
Routes
Based on the previous db.json
file, here are all the default routes. Yous tin can also add other routes using --routes
.
Plural routes
GET /posts GET /posts/1 POST /posts PUT /posts/1 PATCH /posts/one DELETE /posts/ane
Atypical routes
GET /profile POST /profile PUT /profile PATCH /profile
Filter
Use .
to access deep properties
Get /posts?title=json-server&author=typicode Become /posts?id=one&id=2 GET /comments?writer.name=typicode
Paginate
Use _page
and optionally _limit
to paginate returned information.
In the Link
header you'll get outset
, prev
, side by side
and last
links.
Become /posts?_page=7 GET /posts?_page=seven&_limit=20
ten items are returned by default
Sort
Add together _sort
and _order
(ascending order by default)
GET /posts?_sort=views&_order=asc Go /posts/1/comments?_sort=votes&_order=asc
For multiple fields, use the post-obit format:
GET /posts?_sort=user,views&_order=desc,asc
Slice
Add _start
and _end
or _limit
(an X-Total-Count
header is included in the response)
Go /posts?_start=20&_end=xxx GET /posts/1/comments?_start=20&_end=thirty Become /posts/ane/comments?_start=20&_limit=ten
Works exactly equally Array.slice (i.e. _start
is inclusive and _end
exclusive)
Operators
Add _gte
or _lte
for getting a range
Become /posts?views_gte=10&views_lte=20
Add _ne
to exclude a value
GET /posts?id_ne=one
Add _like
to filter (RegExp supported)
GET /posts?title_like=server
Full-text search
Add q
GET /posts?q=net
Relationships
To include children resource, add _embed
Get /posts?_embed=comments GET /posts/1?_embed=comments
To include parent resource, add _expand
GET /comments?_expand=post Get /comments/1?_expand=post
To go or create nested resource (past default one level, add together custom routes for more)
Become /posts/one/comments POST /posts/1/comments
Database
GET /db
Homepage
Returns default alphabetize file or serves ./public
directory
GET /
Extras
Static file server
Yous can apply JSON Server to serve your HTML, JS and CSS, only create a ./public
directory or utilize --static
to prepare a different static files directory.
mkdir public repeat 'hello world' > public/index.html json-server db.json
json-server db.json --static ./some-other-dir
Culling port
You tin commencement JSON Server on other ports with the --port
flag:
$ json-server --watch db.json --port 3004
Access from anywhere
You tin can access your fake API from anywhere using CORS and JSONP.
Remote schema
You can load remote schemas.
$ json-server http://example.com/file.json $ json-server http://jsonplaceholder.typicode.com/db
Generate random data
Using JS instead of a JSON file, you tin can create data programmatically.
// index.js module . exports = ( ) => { const data = { users: [ ] } // Create 1000 users for ( permit i = 0 ; i < k ; i ++ ) { data . users . push button ( { id: i , proper noun: `user ${ i } ` } ) } return information }
Tip utilise modules like Faker, Coincidental, Chance or JSON Schema Faker.
HTTPS
There are many means to set up SSL in development. One simple way is to use hotel.
Add together custom routes
Create a routes.json
file. Pay attention to start every road with /
.
{ "/api/*" : "/$ane" , "/:resource/:id/show" : "/:resource/:id" , "/posts/:category" : "/posts?category=:category" , "/articles\\?id=:id" : "/posts/:id" }
Beginning JSON Server with --routes
option.
json-server db.json --routes routes.json
Now y'all can admission resources using additional routes.
/api/posts # → /posts /api/posts/1 # → /posts/i /posts/1/show # → /posts/1 /posts/javascript # → /posts?category=javascript /manufactures?id=1 # → /posts/1
Add middlewares
You can add together your middlewares from the CLI using --middlewares
option:
// how-do-you-do.js module . exports = ( req , res , side by side ) => { res . header ( '10-Hello' , 'World' ) next ( ) }
json-server db.json --middlewares ./hi.js json-server db.json --middlewares ./kickoff.js ./second.js
CLI usage
json-server [options] <source> Options: --config, -c Path to config file [default: "json-server.json"] --port, -p Set port [default: 3000] --host, -H Set host [default: "localhost"] --sentinel, -w Watch file(s) [boolean] --routes, -r Path to routes file --middlewares, -m Paths to middleware files [array] --static, -south Set static files directory --read-merely, --ro Allow merely GET requests [boolean] --no-cors, --nc Disable Cross-Origin Resource Sharing [boolean] --no-gzip, --ng Disable GZIP Content-Encoding [boolean] --snapshots, -Southward Prepare snapshots directory [default: "."] --delay, -d Add delay to responses (ms) --id, -i Set database id property (e.g. _id) [default: "id"] --foreignKeySuffix, --fks Prepare foreign central suffix, (east.g. _id equally in post_id) [default: "Id"] --quiet, -q Suppress log messages from output [boolean] --help, -h Show help [boolean] --version, -v Show version number [boolean] Examples: json-server db.json json-server file.js json-server http://case.com/db.json https://github.com/typicode/json-server
You lot can likewise set options in a json-server.json
configuration file.
Module
If yous need to add together hallmark, validation, or any behavior, y'all can use the project as a module in combination with other Limited middlewares.
Simple example
$ npm install json-server --save-dev
// server.js const jsonServer = require ( 'json-server' ) const server = jsonServer . create ( ) const router = jsonServer . router ( 'db.json' ) const middlewares = jsonServer . defaults ( ) server . use ( middlewares ) server . use ( router ) server . listen ( 3000 , ( ) => { panel . log ( 'JSON Server is running' ) } )
The path you provide to the jsonServer.router
office is relative to the directory from where you launch your node procedure. If yous run the above code from another directory, information technology'southward better to utilize an absolute path:
const path = require ( 'path' ) const router = jsonServer . router ( path . join ( __dirname , 'db.json' ) )
For an in-retentiveness database, just pass an object to jsonServer.router()
.
Delight note likewise that jsonServer.router()
can be used in existing Express projects.
Custom routes example
Let's say yous want a route that echoes query parameters and some other one that gear up a timestamp on every resource created.
const jsonServer = require ( 'json-server' ) const server = jsonServer . create ( ) const router = jsonServer . router ( 'db.json' ) const middlewares = jsonServer . defaults ( ) // Gear up default middlewares (logger, static, cors and no-cache) server . use ( middlewares ) // Add together custom routes before JSON Server router server . get ( '/echo' , ( req , res ) => { res . jsonp ( req . query ) } ) // To handle POST, PUT and PATCH y'all need to utilize a trunk-parser // Y'all tin utilise the one used by JSON Server server . use ( jsonServer . bodyParser ) server . use ( ( req , res , next ) => { if ( req . method === 'POST' ) { req . body . createdAt = Date . at present ( ) } // Keep to JSON Server router next ( ) } ) // Apply default router server . use ( router ) server . mind ( 3000 , ( ) => { console . log ( 'JSON Server is running' ) } )
Access control case
const jsonServer = crave ( 'json-server' ) const server = jsonServer . create ( ) const router = jsonServer . router ( 'db.json' ) const middlewares = jsonServer . defaults ( ) server . use ( middlewares ) server . utilize ( ( req , res , next ) => { if ( isAuthorized ( req ) ) { // add your say-so logic here next ( ) // go on to JSON Server router } else { res . sendStatus ( 401 ) } } ) server . use ( router ) server . listen ( 3000 , ( ) => { console . log ( 'JSON Server is running' ) } )
Custom output instance
To alter responses, overwrite router.render
method:
// In this example, returned resources volition be wrapped in a body property router . render = ( req , res ) => { res . jsonp ( { body: res . locals . information } ) }
You can set your own status code for the response:
// In this instance we simulate a server side error response router . render = ( req , res ) => { res . status ( 500 ) . jsonp ( { mistake: "fault message hither" } ) }
Rewriter instance
To add together rewrite rules, employ jsonServer.rewriter()
:
// Add together this before server.use(router) server . use ( jsonServer . rewriter ( { '/api/*': '/$i' , '/web log/:resource/:id/evidence': '/:resource/:id' } ) )
Mounting JSON Server on some other endpoint example
Alternatively, yous tin also mount the router on /api
.
server . use ( '/api' , router )
API
jsonServer.create()
Returns an Express server.
jsonServer.defaults([options])
Returns middlewares used past JSON Server.
- options
-
static
path to static files -
logger
enable logger middleware (default: true) -
bodyParser
enable torso-parser middleware (default: true) -
noCors
disable CORS (default: false) -
readOnly
accept only GET requests (default: faux)
-
jsonServer.router([path|object])
Returns JSON Server router.
Deployment
Yous can deploy JSON Server. For instance, JSONPlaceholder is an online fake API powered by JSON Server and running on Heroku.
Links
Video
- Creating Demo APIs with json-server on egghead.io
Manufactures
- Node Module Of The Week - json-server
- ng-admin: Add an AngularJS admin GUI to any RESTful API
- Fast prototyping using Restangular and Json-server
- Create a Mock Rest API in Seconds for Prototyping your Frontend
- No API? No Problem! Rapid Development via Mock APIs
- Goose egg Code REST With json-server
Third-political party tools
- Grunt JSON Server
- Docker JSON Server
- JSON Server GUI
- JSON file generator
- JSON Server extension
License
MIT
Supporters
Source: https://www.npmjs.com/package/json-server
0 Response to "Json Server Middle Ware for File Upload"
Post a Comment