typicode / json-server Goto Github PK
View Code? Open in Web Editor NEWGet a full fake REST API with zero coding in less than 30 seconds (seriously)
License: Other
Get a full fake REST API with zero coding in less than 30 seconds (seriously)
License: Other
May we provide information in X-Total-Count like JSON parameter?
In my case: I use ExtJS for build my application. Currently I have problem with getting information from response header.
In my opinion: We can make json-server response like
{ count: .... , data: .... }
I am running the json-server using my own json file. I am able to POST and PUT, and when I do, the server save the changes to the file periodically. Is there any way to specify that the server should save the file whenever there is a change, instead of a time interval? I could not figure out what the time interval is. It seems to be inconsistent.
Thanks in advance,
Jamie
I need to create a mocking server containing some REST routes, and some non-rest routes (command-like routes like POST /login
).
I've tried to mount the json-server app, and went to the point where everything works, except json-server route calls are logged twice:
var express = require('express');
var methodOverride = require('method-override')
var bodyParser = require('body-parser')
var jsonServer = require('json-server');
var cors = require('cors');
var errorhandler = require('errorhandler');
var logger = require('morgan');
var port = process.env.PORT || 3000;
// create http server
var server = express()
server.set('port', port);
server.use(logger('dev'));
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: false }));
server.use(methodOverride());
server.use(cors({ origin: true, credentials: true }));
if (process.env.NODE_ENV === 'development') {
// only use in development
server.use(errorhandler());
}
// custom routes
server.post('/login', function(req, res) {
res.json({name: "John Doe", access_token:"3A364F68DA5745EB653457A585678"});
});
// mount jsonServer
jsonServer.low.db = require('./seed').run();
server.use(jsonServer);
server.listen(port);
console.log('Mock server listening on port ' + port);
console.log('Press CTRL+C to stop server');
I think this is a fairly common use case, and IMO it should be more straightforward. Could you make the logging optional (i.e. if the json-server application is mounted, disable the logging)?
Hi,
Thanks for this module, very, very helpful…
But now I'm pushing it further, I'm stumbling upon some problems.
For example, if you GET /posts/4/comments
and the post with id 4 does not exist the entire comments
resource will be deleted. This happens very inconsistently and I have not been able to debug it so far.
Do you have any idea of what could cause this?
Thanks for your time.
I was wondering if it's possible to do something like GET /member/user or GET /member/user/emails or something so that the REST routes are "subroutes".
I mean add validation based on json-schema.
Hi,
I assume I'm doing something wrong here…
Here is my app.js
:
var server = require('json-server')
var app = server({ schemas: [] }, 'db.json')
app.use(function (req, res, next) {
console.log('Time:', Date.now());
next();
})
app.listen(process.env.PORT || 3000)
This doesn't print anything to the terminal…
Thanks for your time.
Using the wonderful service at http://jsonplaceholder.typicode.com/
var client = new $.RestClient('http://jsonplaceholder.typicode.com/');
var myPost = client.posts.read(10);
client.add('posts');
client.posts.update(102, {title: 'The title!!'}); // <--- this should cause an error
myPost
.done(function (data){
console.log('I have data: ' + data.title);
console.log('I have data: ' + JSON.stringify(data));
})
.fail(function (err){
console.log('err: ' + err);
})
client.show();
Instead of the "fail" callback being triggered, I get this :
PUT http://jsonplaceholder.typicode.com/posts/102/ 500 (Internal Server Error)
Any idea what I am doing wrong? Thanks
Hello and thanks for your great work!
I have a little problem. We use a structure like this:
{
"data": [
{
"id": 1,
"name": "John"
},
{
"id": 2,
"name": "Jake"
},
],
"meta": {
"total": 2,
"page": 1
}
}
Now I can write the structure in my generate.js with the "data" and "meta" keys and it return correctly when I call /user.
Anyway when I try to get a single element of the collection, say /user/1, it returns me an empty object with a 404 http code.
I understand that this is a non-conventional request, but do you think that a situation like that could be handled via some config file or options passed to the CLI?
Thank you.
PATCH method not exposed in response CORS headers:
curl -X OPTIONS -v -H "Access-Control-Request-Method: PATCH" http://localhost:3000/
* About to connect() to localhost port 3000 (#0)
* Trying 127.0.0.1... connected
> OPTIONS / HTTP/1.1
> User-Agent: curl/7.23.1 (x86_64-pc-win32) libcurl/7.23.1 OpenSSL/0.9.8r zlib/1.2.5
> Host: localhost:3000
> Accept: */*
> Access-Control-Request-Method: PATCH
>
< HTTP/1.1 204 No Content
< X-Powered-By: Express
< Access-Control-Allow-Origin: *
< Access-Control-Allow-Methods: GET,HEAD,PUT,POST,DELETE
< Date: Thu, 01 May 2014 04:07:22 GMT
< Connection: keep-alive
<
* Connection #0 to host localhost left intact
* Closing connection #0
Writing an empty string stores a 0
> curl -H "Content-Type: application/json" -X POST http://localhost:3000/posts -d'{"id":6,"comment":""}'
{"id":6,"comment":0}
> curl -H "Content-Type: application/json" -X GET http://localhost:3000/posts/6
{"id":6,"comment":0}
After giving the save command, the snapshot is reported as created however no matching file exists.
$ node index.js db.json
{^ ^} Yo!
Loading database from db.json
http://localhost:3000/referrers
Enter `s` at any time to create a snapshot of the db
s
Saved snapshot to db-1420467984100.json
^C
$ ls
db.json index.js
Hi,
If I get the readme well, it's possible to use POST and PUT to alter content of the db.json ?
Here is my db & server:
// Database
var low = require('lowdb');
low.mixin(require('underscore-db'));
var db = low('db.json');
// Server
var jsonServer = require('json-server');
var router = jsonServer.router(db.object); // Express router
var server = jsonServer.create(); // Express server
server.use(jsonServer.defaults); // Default middleware (logger, public, ...)
server.use(router);
server.listen(3000);
my data in db.json :
"posts": [
{
"id": 1,
"title": "json-server",
"author": "typicode"
}
],
and the request I sent with jQuery on client side :
$.ajax({
method: "POST",
url: "/posts",
data: {"id": 2, "title": "title test"}
});
here is my request visible in chrome dev tools :
General :
Remote Address:127.0.0.1:3000
Request URL:http://127.0.0.1:3000/posts
Request Method:POST
Status Code:200 OK
Response Headers :
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://127.0.0.1:3000
Connection:keep-alive
Content-Length:38
Content-Type:application/json; charset=utf-8
Date:Sun, 26 Apr 2015 21:11:59 GMT
ETag:W/"26-224df703"
Vary:Origin, X-HTTP-Method-Override
X-Content-Type-Options:nosniff
X-Powered-By:Express
Request header :
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:fr,en-GB;q=0.8,en;q=0.6
Connection:keep-alive
Content-Length:21
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
DNT:1
Host:127.0.0.1:3000
Origin:http://127.0.0.1:3000
Referer:http://127.0.0.1:3000/?
User-Agent:Mozilla/5.0 (Windows NT 6.3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36
X-Requested-With:XMLHttpRequest
Form Data :
id:2
title:title test
and the response :
{
"id": 2,
"title": "title test"
}
The problem is : db.json is not updated.
It's weird because when I get to http://127.0.0.1:3000/posts I can see the added post :
[
{
"id": 1,
"title": "json-server",
"author": "typicode"
},
{
"id": 2,
"title": "title test"
}
]
Any idea ?
Thanks :)
Have you ever thought about to create a grunt plugin for this nice tool?
Is it ok for you if i create one?
The body-parser has an (Object) options
parameter that accept a limit - maximum request body size. (default: <100kb>)
, my application have too many data, I have to set this value to 10mb
so I will fork and commit my changes.
That's the error HTTP 413
:
Error: request entity too large
at makeError (/usr/lib/node_modules/json-server/node_modules/body-parser/node_modules/raw-body/index.js:184:15)
at module.exports (/usr/lib/node_modules/json-server/node_modules/body-parser/node_modules/raw-body/index.js:40:15)
at read (/usr/lib/node_modules/json-server/node_modules/body-parser/lib/read.js:62:3)
at urlencodedParser (/usr/lib/node_modules/json-server/node_modules/body-parser/lib/types/urlencoded.js:84:5)
at Layer.handle [as handle_request] (/usr/lib/node_modules/json-server/node_modules/express/lib/router/layer.js:82:5)
at trim_prefix (/usr/lib/node_modules/json-server/node_modules/express/lib/router/index.js:271:13)
at /usr/lib/node_modules/json-server/node_modules/express/lib/router/index.js:238:9
at Function.proto.process_params (/usr/lib/node_modules/json-server/node_modules/express/lib/router/index.js:313:12)
at /usr/lib/node_modules/json-server/node_modules/express/lib/router/index.js:229:12
at Function.match_layer (/usr/lib/node_modules/json-server/node_modules/express/lib/router/index.js:
I found this is interesting, if id is 54958d281a995 instead of an integer, it stop working.
such as returning "200 OK" instead "201 CREATED" after creating a new resource. (POST /resources)
When I saw in the readme that PUT
and POST
requests are supported, I expected that to mean the underlying JSON files can be written to via HTTP. Is that the case?
If not, wouldn't that be cool?!
Given the following JSON:
{
"speakers": [
{
"id": 1,
"name": "Bugs Bunny"
},
{
"id": 2,
"name": "Wile E. Coyote"
},
{
"id": 3,
"name": "Yosemite Sam"
}
]
}
Is it possible to run json-server
such that it responds to /api/v1/speakers
rather than /speakers
?
Node v 0.10.24, json-server v 0.3.1
Invoking "json-server" as node module:
var server = require('json-server'),
db = require('./seed').run();
var options = { port: 4000, readOnly: true };
server.run(db, options);
returns error:
server.run(db, options);
^
TypeError: Object function app(req, res, next){ app.handle(req, res, next); } has no method 'run'
at Object. (/home/darek/testbox/json-server/index.js:6:8)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
When I'm lauching the server-json I get this error:
TypeError: Object #<Chalk> has no method 'grey'
at start (/home/giacomo/lib/node_modules/json-server/bin/index.js:41:23)
at Object.<anonymous> (/home/giacomo/lib/node_modules/json-server/bin/index.js:83:3)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3
I'm missing something?
Thanks
Create routes and responses that follow http://jsonapi.org/
Hi! Thanks for JSON Server; it's awesome.
I've got a use case where I'm trying to run a json-server express instance, but I need to add some additional middleware before the static file handling gets added to the middleware stack. I began work toward enabling this, but was debating between a few varying solutions, so before I go any further I thought I'd ping you for your thoughts. Firstly, would you be on board with this enhancement? If so, I was thinking any of the following made sense:
create
to accept a callback. This callback would receive the express()
server as an argument, which it could then use to do any configuration needed.#1
, update create
to accept an options
object with a designated callback (e.g., options.preconfigure
) to do the same configuration. This solution is arguably more future-proof.create
to accept an optional express server instance, defaulting back to express()
like it does currently. The downside to this is that it puts the onus of express dependency management on the user instead of in json-server.Thoughts? I'd be happy to submit a PR for this.
Any way to add a setting/feature that would return 404 status codes instead of []
for unmatched GET requests? I imagine that the 200 response is useful for most people, but it would aid rapid development with json-server
if we knew that we mistyped something.
My specific use case is in leveraging the ./public
static file serving feature and not getting warnings that we're looking for something that doesn't exist yet.
The boolean values, in a PUT request data load, gets stored as 0 or 1 (for false and true respectively). On research, I found in routes.js, there is a call to toNative method from utils module. The toNative method converts boolean literal values to integer numbers like 0 or 1.
I think the toNative method should convert only the string values to its native equivalent.
Please advise.
While reading the README I noticed that under the Routes section you recommend to use _start
and _end
but use _start
and end
in the example just below.
So I have a json file that has the following schema:
{
"environments": [
{
"id": 12,
"reports": [
{
"id": 17
},
{
"id": 25
}
]
},
{
"id": 19,
"reports": [
{
"id": 22
},
{
"id": 30
}
]
}
]
}
/environments
works, as does /environments/12
, so I figured I could use the route /environments/12/reports
to return that array, but it's returning a 404 instead. Am I doing something wrong here?
My env:
🍻
Trying to run json-server in CMD on a Windows 8.1 VM:
C:\path\to\webroot>json-server mockAPI.json
{^ ^} Yo!
Loading database from mockAPI.json
http://localhost:3000/issues
Enter `s` at any time to create a snapshot of the db
undefined:1
´╗┐{
^
SyntaxError: Unexpected token ´╗┐
at Object.parse (native)
at Function.low.parse (C:\Users\peqe\AppData\Roaming\npm\node_modules\json-server\node_modules\lowdb\src\index.js:80:15)
at new Low (C:\Users\peqe\AppData\Roaming\npm\node_modules\json-server\node_modules\lowdb\src\index.js:17:24)
at low (C:\Users\peqe\AppData\Roaming\npm\node_modules\json-server\node_modules\lowdb\src\index.js:61:10)
at module.exports (C:\Users\peqe\AppData\Roaming\npm\node_modules\json-server\src\create-routes.js:12:14)
at module.exports (C:\Users\peqe\AppData\Roaming\npm\node_modules\json-server\src\index.js:30:16)
at start (C:\Users\peqe\AppData\Roaming\npm\node_modules\json-server\bin\index.js:48:3)
at Object.<anonymous> (C:\Users\peqe\AppData\Roaming\npm\node_modules\json-server\bin\index.js:60:3)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
What do you think of implementing the standards?
When using json-server db.json
, if db.json is changed, the server will still return old data. It can be better if it is able to watch file change and refresh server data automatically.
I would like some random data.
I creat db.js:
module.exports = function() {
data = { };
data.id = Math.floor( Math.random()*9+1 );
return data;
};
but still return old data
What should I do ?
In the documentation it says that issuing "GET /" should return default index file or content of ./public/index.html (useful if you need to set a custom home page). However, even though I have installed json-server according to the provided instructions, I don't have a public folder in my web root.
By the way, can I put my .json file anywhere I want, or does it have to be in the web root? To which folder will http://localhost:3000 point?
I am using a Windows 8.1 VM for this project.
I am providing json file as a db source containing post elements as in : https://gist.github.com/injulkarnilesh/4cfd42501bfd5c13885f
Rest of the calls work fine
GET /posts/
GET /posts/3
POST /posts/
These calls work as expected.
But on
DELETE /posts/3
Response says
Response does not contain any data.
with status 204.
and json data in the file gets emptied to
{
"posts": []
}
Shouldn't it delete only the mentioned post rather than all the posts?
For example, I want usernames to be user IDs, like /users/iamale
.
Hello! I've mounted json-server on an existing Express Server in this way:
var express = require('express');
var jsonServer = require('json-server');
var app = express();
app.use(express.static(__dirname + '/public'));
app.set('view engine', 'jade');
// Route index
app.get('/', function (req, res) {
res.render('index');
});
var router = jsonServer.router(require('./api.js')());
app.use(router);
app.listen(3000, function() {
console.log('Static server and APIs listening on port 3000');
});
Now when I call a POST route on this server I receive this error:
TypeError: Cannot read property 'id' of undefined
at Function.module.exports.insert (D:\projects\api\node_modules\json-server\node_modules\underscore-db\src\index.js:45:12)
While if I start json-server stand alone json-server api.js
everything works as expected and I receive the newly created items as reponse.
I've made some mistakes with my Express server? Is there a better way to integrate json-server with Express? Thank you.
Add delay option to return requests. Just to be able to test in a more real way.
Hi,
given a database like
"keywords": [
{
"id": 0,
"entity": "messages",
"entityId": 5,
"value": "mollit"
},
{
"id": 1,
"entity": "messages",
"entityId": 1,
"value": "consequat"
}
]
if I delete an item with DELETE /keywords/1
, then all keywords are deleted. If I rename entityId to entityRef, everything is fine.
Is there any way I can specify that entityId is not a foreign key ?
Thanks,
Alain
This (awesome) projects don't let you use integer ids.
In other words, you can provide something like:
{
"posts": [
{ "id": "1", "body": "foo" },
{ "id": "2", "body": "bar" }
],
"comments": [
{ "id": "1", "body": "baz", "postId": "1" },
{ "id": "2", "body": "qux", "postId": "2" }
]
}
If you visit /posts it works, but if you try to get /posts/1 you get no results.
Sometimes it is useful having string identifiers or when you have to simulate an existing environment.
Does it make sense for you? Is there a workaround for this?
This is awesome. Thanks for your work here! Wondering how you/if you would go about setting up some sort of fake authentication system. Specifically, I want to use JWT. Do you think there's room for something like this in this project?
Out of the box, I got this error:
$ json-server issues.json
module.js:340
throw err;
^
Error: Cannot find module 'low'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object. (/usr/local/lib/node_modules/json-server/src/cli.js:5:15)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
after git clone
and npm install
and node ./bin/index.js
, the full text search is not working.
db.json using:
{
"posts": [
{
"id": 1,
"title": "json-server",
"author": "typicode"
}
],
"comments": [
{
"id": 1,
"body": "some comment",
"postId": 1
}
]
}
Query using:
GET http://localhost:3000/post?q=json-server
It appears that the below code didn't run into the array = db().filter()
and for loop is not running at all:
if (req.query.q) {
// Full-text search
var q = req.query.q.toLowerCase()
array = db(req.params.resource).filter(function(obj) {
for (var key in obj) {
var value = obj[key]
if (_.isString(value) && value.toLowerCase().indexOf(q) !== -1) {
return true
}
}
})
} else {
Can anyone tell me how to get full text search working?
When I post a json with numeric values in it, e.g.
$.post("http://localhost:3000/test", {x:1,y:2}, 'json');
json-server stores the values as strings:
{"x":"1","y":"2"}
,which is a problem for me because the filter won't work with string values:
http://localhost:3000/test?x=1
I did a quick and dirty fix by adding:
for (var key in req.body)
req.body[key] = utils.toNative(req.body[key]);
...at the start of routes.create and routes.update
Sample image link http://localhost:3000/assets/images/coffee/large/coffee.gif
not working with json-server, it's not possible to server static assets? (script files, css styles, images)
Or is there any way to plug sharp
(image resizer node package) into json-server
Hey again :)
I'm working on https://github.com/Shuunen/pracker
The aim of this tool is to watch a product price on the web and update a UI to alert the user when a product price changed.
So I use lowdb and json-server on the same file and you can see my implementation here : https://github.com/Shuunen/pracker/blob/master/pracker.js
On line 51 I added a "foo bar" test : product.toto = 42;
By db.json file is never updated with this.
But, if I comment the //Server init :
// Server
var jsonServer = require('json-server');
var router = jsonServer.router(dbFile);
var server = jsonServer.create();
server.use(jsonServer.defaults);
server.use(router);
server.listen(3000);
I will find my product.toto = 42 in db.json
So I think json-server is locking the file and prevent lowdb from updating, right ?
I installed json-server globally and I followed the instruction to make a test json file:
{ "people": [ { "fname": "Bashar", "lname": "Ayyash" } ] }
When I started json-server I received the following error:
C:\Program Files\nodejs\node_modules\json-server\bin\index.js:54
server(object, filename).listen(port)
^
TypeError: object is not a function
at start (C:\Program Files\nodejs\node_modules\json-server\bin\index.js:54:3)
at Object. (C:\Program Files\nodejs\node_modules\json-server\bin\index.js:68:3)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:929:3
Why is this?
Please advice,
Would be very useful to serve directory, rather than 1 file. Say you got accounts.json
, and flight.json
, would be great to call something json server src/app/db/.
and ability to call localhost:3000/accounts
for accounts file
Can custom routes be added?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.