json-server | Get a full fake REST API with zero coding in less than 30 seconds (seriously) | REST library
kandi X-RAY | json-server Summary
Support
Quality
Security
License
Reuse
- list resource names
- Start the server
- Creates a new app .
- Update a resource .
- Get a list of references from the collection .
- get page object
- Display a resource
- Prints the list of resources
- Remove document related to the database
- Block to produce custom routes
json-server Key Features
json-server Examples and Code Snippets
npm install -g json-server
npx json-server --watch db.json
FROM node:10-alpine as build-step
RUN mkdir -p /app
WORKDIR /app
COPY package.json /app
RUN npm install
COPY . /app
RUN npm run build --prod
# Stage 2
FROM nginx:1.17.1-alpine
COPY nginx.conf /etc/nginx/nginx.conf
COPY --from=build-step /app/dist/my-app /usr/share/nginx/html
RUN npm install json-server
CMD json-server --watch services/mock-api/db.json --routes services/mock-api/routes.json --port 3000 --host 0.0.0.0
// api-routes.js
const express = require('express')
const jsonServer = require('json-server')
const router = express.Router()
const server = jsonServer.create()
const middlewares = jsonServer.defaults()
const v1Router = jsonServer.router('db-v1.json')
const v2Router = jsonServer.router('db-v2.json')
router.use('/v1', v1Router)
router.use('/v2', v2Router)
module.exports = router
const express = require('express')
const apiRoutes = require('./api-routes')
const app = express()
app.use('/api', apiRoutes)
// ...
# Stage 1
FROM node:10-alpine as build-step
RUN mkdir -p /app
WORKDIR /app
COPY package.json /app
RUN npm install
COPY . /app
RUN npm run build --prod
# Stage 2
FROM ubuntu:16.04
USER root
WORKDIR /home/app
COPY package.json /home/app/package.json
RUN apt-get update
RUN apt-get -y install curl gnupg
RUN curl -sL https://deb.nodesource.com/setup_11.x | bash -
RUN apt-get -y install nodejs
RUN apt update
RUN apt-get -y install nginx
RUN npm i -g json-server
COPY nginx.conf /etc/nginx/nginx.conf
COPY --from=build-step /app/dist/my-app/usr/share/nginx/html
CMD json-server --watch /usr/share/nginx/html/assets/mock-api/db.json --routes /usr/share/nginx/html/assets/mock-api/routes.json --no-cors --host 0.0.0.0
FROM node:lts-slim
RUN npm install -g json-server
WORKDIR /data
VOLUME /data
EXPOSE 3000
ADD entrypoint.sh /entrypoint.sh
ENTRYPOINT ["bash", "/entrypoint.sh"]
CMD []
#!/bin/bash
args="$@"
args="$@ --host 0.0.0.0 --port 3000"
file=/data/db.json
if [ -f $file ]; then
echo "Found $file"
args="$args --watch $file"
fi
echo "json-server $args"
json-server $args
json-server:
build: ./json-server
volumes:
- ./json-server/json/:/data
ports:
- 3000:3000
var express = require('express');
var jsonServer = require('json-server');
var app = express();
//publish the static result of npm run build (vue)
//https://github.com/jrichardsz/nodejs-express-snippets/tree/master/simple-static-server
app.use('/',
express.static(path.join(__dirname, "site" || proces.env.SITE_FOLDER)),
);
//run json-server programmatically here
//https://github.com/typicode/json-server/issues/253#issuecomment-205509836
app.use('/api', jsonServer.router('db.json'));
app.listen(3000);
version: '3'
services:
json-server:
image: json-server-image:latest
ports:
- "3000:3000"
container_name: json-server
hostname: json-server
networks:
- some-net
angular:
image: angular-image:latest
ports:
- "8888:80"
container_name: angular
networks:
- some-net
networks:
some-net:
driver: bridge
networks:
some-net:
driver: bridge
networks:
- some-net
npm i -D @angular-builders/custom-webpack json-server
ng config projects..architect.build.builder @angular-builders/custom-webpack:browser
ng config projects..architect.build.options.customWebpackConfig.path custom-webpack.config.js
ng config projects..architect.serve.builder @angular-builders/custom-webpack:dev-server
ng config projects..architect.serve.options.customWebpackConfig.path custom-webpack.config.js
const json = require('json-server');
module.exports = {
devServer: {
before: function(app) {
app.use('/api', json.router('db.json'));
}
}
};
{
"users": []
}
const API = '/api/users/';
@Injectable({
providedIn: 'root'
})
export class AppService {
constructor(private http: HttpClient) {}
get(id: number) {
return this.http.get(API + id);
}
post(user: any) {
return this.http.post(API, user);
}
}
npm install -g json-server
echo '{"logs": []}'> logs.json
json-server logs.json
let veryLargeTextWorks = "1234567890";
for (let i = 0; i < 11; i++) {
veryLargeTextWorks += veryLargeTextWorks;
}
// veryLargeTextWorks.length == 20480
axios.post("http://localhost:3000/logs", {
date: new Date(),
msg: veryLargeTextWorks
});
Trending Discussions on json-server
Trending Discussions on json-server
QUESTION
My setter, for SetPersons, seems to keep adding empty elements into its array for no apparent reason. I am trying to make my phone number list update instantaneously when I update a user's number but it sticks with the old number. Whenever I apply the logic to possibly make the number update instantly, it adds empty elements into my array instead and does not update instantly. Here is the code for each separate component:
App.js
import { useEffect, useState, useRef} from 'react'
import PersonForm from './components/PersonForm'
import Display from './components/Display'
import Filter from './components/Filter'
import phoneService from './services/information'
const App = () => {
const [errorMessage, setErrorMessage] = useState('')
const [persons, setPersons] = useState('')
const [newName, setNewName] = useState('')
const [newNumber, setNewNumber] = useState('')
const [filter, setFilter] = useState('')
const [filterChecker, setFilterChecker] = useState('')
useEffect(() => {
phoneService.getAll()
.then(people => setPersons(people))
}, [])
const handleSubmit = (e) => {
e.preventDefault();
const copy = [...persons]
const foundNameOrNot = persons.some(el => el.name === newName)
const foundNumberOrNot = persons.some(el => el.number === newNumber)
const eachPersonsID = persons.map(person => person.id)
const newObj = {
name: newName,
number: newNumber,
id: Math.max(eachPersonsID) + 1
}
if (foundNameOrNot) {
if(window.confirm(`${newName} is added to phonebook, replace the old number with a new one.`)) {
const indexFinder = persons.filter(person => person.name === newName)
newObj.id = indexFinder[0].id
copy[indexFinder[0].id] = newObj
phoneService.update(indexFinder[0].id, newObj)
.then(res => {
setErrorMessage(`Successfully updated ${newName}s number`)
setPersons([copy])})
.catch(err => {
setErrorMessage(`Information on ${newName} has already been removed`)
setFilterChecker(filterChecker.filter(filter => filter !== newName))})
}
} else if (foundNumberOrNot) {
alert(`${newNumber} belongs to someone else`)
} else {
phoneService.create(newObj).then(res => setPersons([...persons, newObj]))
}
}
const handleFilter = (e) => {
console.log(persons)
setFilter(e.target.value)
const allNames = persons.map(person => person.name)
setFilterChecker(allNames.filter(name => name.toLowerCase().indexOf(filter.toLowerCase()) !== -1))
}
return (
{errorMessage ? errorMessage : ''}
Phonebook
add a new
add
Numbers
)
}
export default App
Display.js
import phoneService from '../services/information'
import axios from 'axios'
import { useState } from 'react'
const handleDelete = (i, persons, setPersons, name2, setFilterChecker, errorMessage, setErrorMessage) => {
if (window.confirm(`delete ${name2} ?`)) {
const newArrayOfPeople = persons.filter(person => person.name !== name2)
const newArrayOfNames = newArrayOfPeople.map(person => person.name)
setFilterChecker(newArrayOfNames)
setPersons(newArrayOfPeople)
phoneService.remove(persons[i].id)
setErrorMessage(`You have successfully deleted ${name2} from the list.`)
setTimeout(() => {
setErrorMessage(null)
}, 5000)
}
}
const Display = ({filterChecker, persons, setPersons, setFilterChecker, errorMessage, setErrorMessage}) => {
const copy = [...persons]
const findNumbers = []
const findNames = []
for (let j = 0; j < copy.length; j++) {
if (copy[j]?.name && !findNames.includes(copy[j]?.name)) {
findNames.push(copy[j].name)
}
}
for (let i = 0; i < copy.length; i++) {
if (copy[i]?.number && !findNumbers.includes(copy[i]?.number)) {
findNumbers.push(copy[i]?.number)
}
}
if (filterChecker) {
return (
findNames.map((name, i) => {name} {findNumbers[i]} handleDelete(i, persons, setPersons, name, setFilterChecker, errorMessage, setErrorMessage)}>delete)
)
} else {
return ''
}
}
export default Display
Filter.js
const Filter = ({filter, handleFilter}) => {
return filter shown with
}
export default Filter
PersonForm.js
import axios from 'axios';
import phoneService from '../services/information'
const PersonForm = ({newName, newNumber, setNewName, setNewNumber}) => {
return (
name: setNewName(e.target.value)}/>
number: setNewNumber(e.target.value)}/>
)
}
export default PersonForm
information.js
import axios from "axios"
const baseUrl = 'http://localhost:3002/numbers'
const getAll = () => {
const request = axios.get(baseUrl)
return request.then(response => response.data)
}
const create = newObject => {
const request = axios.post(baseUrl, newObject)
return request.then(response => response.data)
}
const update = (id, newObject) => {
const request = axios.put(`${baseUrl}/${id}`, newObject)
return request.then(response => response.data)
}
const remove = (id) => {
const request = axios.delete(`${baseUrl}/${id}`)
return request.then(res => res.data)
}
export default { getAll, create, update, remove, baseUrl }
My json-server "db.json"
{
"numbers": [
{
"name": "uvaldo",
"number": "20",
"id": 6
},
{
"name": "uvaldo zumaya",
"number": "24",
"id": 7
},
{
"name": "uvaldo zumaya d",
"number": "26",
"id": 8
}
]
}
Whenever I try to update "uvaldo" phone number to 22, it just stays at 21 then throws errors, this picture is before I hit "add" to avoid the program crashing...
ANSWER
Answered 2022-Apr-18 at 01:06There are issues with the logic where you update persons
.
Try this instead:
const handleSubmit = (e) => {
...
const indexFinder = persons.findIndex(person => person.name === newName)
newObj.id = persons[indexFinder].id
copy[indexFinder] = newObj
phoneService.update(persons[indexFinder].id, newObj)
.then(res => {
setErrorMessage(`Successfully updated ${newName}s number`)
setPersons(copy)})
...
}
The reason why it was adding empty elements is that the index used to place newObj
was greater than the size of the array:
copy[indexFinder[0].id] = newObj
Also note that person.id
does not necessarily mean that they are in that index of the array persons
.
QUESTION
I'm using json-server as my local server for a nuxt project and i want to automatically launch the server and then run the project on another shell instance using "npm run dev"
in the scripts tag in package.json this is what i came up with :
"dev": "json-server --watch db.json --port 3004 & nuxt"
but this script only starts the server
ANSWER
Answered 2022-Mar-23 at 11:29try concurrently
npm install -g concurrently
"dev": "concurrently \"json-server --watch db.json --port 3004\" \"nuxt""
QUESTION
Learning reactjs, trying to simulate a server with json-server
this is my script to run the server:
"scripts": {
"server": "json-server --watch db.json --port 5000"
},
running this on terminal npm run server
output:
Debugger listening on ws://127.0.0.1:61616/507f7893-92a9-4526-b8f4-a3e71cfa4c62
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.
> my-app@0.1.0 server
> json-server --watch db.json --port 5000
Debugger listening on ws://127.0.0.1:61629/8a2f877f-f4bd-465e-b454-01a63eabb40a
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.
\{^_^}/ hi!
Loading db.json
Done
Resources
http://localhost:5000/tasks
Home
http://localhost:5000
Type s + enter at any time to create a snapshot of the database
Watching...
now when I try to access http://localhost:5000/tasks , I get 403 Access to localhost was denied.
what can I do to fix this?
Thanks!
ANSWER
Answered 2021-Dec-18 at 13:15the problem was with the port. changed it to 3001 and it works. still doesn't understand why did this happen in that port.
QUESTION
Image of the error This is the error that I am continuously getting after numerous tries. I tried removing node cache, I re-installed node.js but couldn't find success. However, whenever I am running it with administrator or root, I am able to install it. So why is this happening?
I have provided the screenshot of my error, however, still, I will provide the error in writing.
npm ERR! code EPERM
npm ERR! syscall mkdir
npm ERR! path C:\Program Files\nodejs\node_modules\json-server
npm ERR! errno -4048
npm ERR! Error: EPERM: operation not permitted, mkdir 'C:\Program Files\nodejs\node_modules\json-server'
npm ERR! [Error: EPERM: operation not permitted, mkdir 'C:\Program Files\nodejs\node_modules\json-server'] {
npm ERR! errno: -4048,
npm ERR! code: 'EPERM',
npm ERR! syscall: 'mkdir',
npm ERR! path: 'C:\\Program Files\\nodejs\\node_modules\\json-server'
npm ERR! }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It's possible that the file was already in use (by a text editor or antivirus),
npm ERR! or that you lack permissions to access it.
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\7386-85615SG 2913642\AppData\Local\npm-cache\_logs\2021-09-03T06_29_38_211Z-debug.log
ANSWER
Answered 2021-Sep-03 at 07:58Try running this command: npm config set unsafe-perm=true
If that doesn't work for you, try changing the folder permissions for your current user for C:\Program Files\nodejs
with the help of this
QUESTION
Attempting to make a HTTP GET
request for posts filtered by query parameter authorId=x
where x
may be a number that may not correspond to any post's authorId
.
json-server
unexpectedly returns HTTP 200
instead of HTTP 404
response when there are no posts with a matching authorId
(i.e., an empty array is returned), how can this be changed to return 404
? Similarly, what would be the best API practice here, would it be to return an empty array with HTTP 400
as json-server
already does or would returning the empty array with HTTP 404
be more clear for users?
I've looked at jsonServer.rewriter
& express
middleware (e.g., json-server
documentation shows it can be configured with middleware such as server.use(middlewares)
) but wanted to ask what the best approach would be here (useful resources/links would be appreciated here), e.g., with middleware, an option is sending 404
for an empty array but does json-server
have an builtin ways to handle this or is there a better approach?
All constructive feedback is welcome, thanks.
Codedb.json
:
{
"posts": [
{
"authorId": 0,
"content": "Foo bar"
},
],
}
Shell:
json-server --watch db.json
REST:
// Response status is expected HTTP 200.
GET http://localhost:5000/posts?authorId=0
This returns the user with HTTP 200
as expected:
[
{
"authorId": 0,
"content": "Foo bar",
}
]
// Response status is unexpected HTTP 200 but 404 was expected since response body contains an empty array. This is the problem.
GET http://localhost:5000/posts?authorId=does_not_exist
This returns an empty array with HTTP 200
, which is possibly unexpected (uncertain on what the best practice is regarding filtered collections where there's no match, but what would be the best practice here & how can the status be changed to HTTP 400
:
[]
ANSWER
Answered 2022-Feb-24 at 18:42As @kindall pointed out, probably ill-advised to return 404, but perhaps this is the existing behavior of the API you're mocking. You can return custom output - from docs: https://github.com/typicode/json-server#custom-output-example
// In this example we simulate a server side error response
router.render = (req, res) => {
res.status(500).jsonp({
error: "error message here"
})
}
For your example, it would probably be something like (untested pseudo-code):
// In this example we return 404 for no content
router.render = (req, res) => {
if (res.locals.data.posts.length < 1) {
res.status(404).jsonp({
error: "no posts"
});
} else {
res.jsonp(res.locals.data);
}
}
QUESTION
I'm pretty sure doing everything correctly. I'm using these version:
"axios": "^0.24.0",
"json-server": "^0.17.0",
I've followed the official doc. I've db.json
in the root folder itself.
{
"users": [
{
"ID": 1,
"Username": "mike",
"Password": "User1Password"
},
{
"ID": 2,
"Username": "robert",
"Password": "User2Password"
}
]
}
I'm running json-server
with this command: json-server --watch db.json --port 4000
Whenever I hit http://localhost:4000/users
I'm served with this:
\{^_^}/ hi!
Loading db.json
Done
Resources
http://localhost:4000/posts
http://localhost:4000/comments
http://localhost:4000/profile
Home
http://localhost:4000
Type s + enter at any time to create a snapshot of the database
Watching...
GET /users 404 4.800 ms - 2
But rest of the end points like:
http://localhost:4000/posts
http://localhost:4000/comments
http://localhost:4000/profile
are working absolutely fine. Please help.
ANSWER
Answered 2021-Oct-30 at 03:31According to @user2740650
You said db.json is in src folder. What matters is that it's in the same folder where you started the server. It sounds like it created a default db.json somewhere else and is using that.
Second Scenario
move your db.json file into the Public folder and calling it by: axios.get('db.json') .then(//...)
QUESTION
I am trying to install JSON-Server, but it's not working!
I have used the following command: npm install -g json-server
Here is the error message:
npm ERR! code EACCES
npm ERR! syscall mkdir
npm ERR! path /usr/local/lib/node_modules/json-server
npm ERR! errno -13
npm ERR! Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/json-server'
npm ERR! [Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/json-server'] {
npm ERR! errno: -13,
npm ERR! code: 'EACCES',
npm ERR! syscall: 'mkdir',
npm ERR! path: '/usr/local/lib/node_modules/json-server'
npm ERR! }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It is likely you do not have the permissions to access this file as the current user
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator.
ANSWER
Answered 2021-Nov-23 at 13:06Try to use sudo before command :
sudo npm install -g json-server
QUESTION
I have installed the json-server
in my Angular app which enables me to save a form (filled by the user) via a fake json API into a json file:
{
"extracts": [
{
"contentName": "xxx",
"contentType": "xxx",
"contentToStore": "xxx",
"id": 1
}
]
}
I can also see the results at my http://localhost:3000/extracts
In my html
template, my form is submitted:
In the corresponding component, I have written this code:
onSubmitExtractions(postData: Post) {
this
.dbService
.submitExtractions(postData)
.subscribe(
postData => {
this.jsonPosts.push(postData);
}
);
this
.dbService
.downloadExtractions(postData);
}
The first snippet writes to the json file, with this code in the service script:
submitExtractions(post: Post): Observable {
return this.httpClient.post(this.apiUrl, post, httpOptions);
}
This works fine and I get the results in a json file (fake json server database) and the second snippet is supposed to download this file whose code in the service script is this:
downloadExtractions(post: Post) {
const blob = new Blob([JSON.stringify(post, null, 2)], { type: 'application/json' });
if (blob) {
this.downloaded = 'The blob contains ' + blob.size + ' byte!';
} else {
this.downloaded = 'The download failed!';
}
}
What am I missing in ths code in order to actually download the json content? How do I download this content as a csv or json or even a text file?
ANSWER
Answered 2021-Oct-13 at 09:21Please try this solution. It is using the same blob just with some constant data.
in html
in component.ts
export class AppComponent implements OnInit {
name = 'Angular 5';
fileUrl;
constructor(private sanitizer: DomSanitizer) { }
ngOnInit() {
const data = 'some text';
const blob = new Blob([data], { type: 'application/octet-stream' });
this.fileUrl = this.sanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(blob));
}
}
For reference, please visit:
https://stackblitz.com/edit/angular-blob-file-download-text-file?file=app%2Fapp.component.ts
QUESTION
what is -w
in here means ?
"db": "json-server -w db.json -p 3001"
this is the package .json file
{
"name": "jsonserver",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"db": "json-server -w db.json -p 3001",
"tunnel": "ngrok http 3001"
},
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^0.24.0",
"json-server": "^0.17.0",
"ngrok": "^4.2.2"
}
}
and i am doing this for a react-native
project what does -w
means?
ANSWER
Answered 2021-Nov-16 at 09:23--watch, -w Watch file(s) [boolean]
QUESTION
As I develop the backend side, I also develop the frontend. As you have probably guessed, I have to do some REST requests on my server.
Well, there are a couple of solutions for that. I can use mocks on the frontend, or a fake JSON server. However, there are some cons to this approach:
- I have to remodel what I have on an already existing backend server.
- Dealing with authentication on a fake JSON server is not really comfortable.
- I have to write a lot of boilerplate if I want to go on mocking and unit testing approach.
Again, all the logic I want already exists in my Django project, so what I want is:
- Run a dev server.
- Set up a fresh new database.
- Provide some initial data. Some fake users, posts, whatever.
- Do my testing on my frontend project while the server runs.
- Hit the kill signal. (CTRL+C)
- Gracefully drop the database that I have created on step 2.
- Shutdown the program.
I use pytest
and pytest-django
. They do exactly these when they set up a test environment, I was wondering if I can manually do that.
Thanks in advance.
Environment- Python 3.9
- Django 2.2
ANSWER
Answered 2021-Nov-16 at 11:12I never used such integration-testing setup, but I’ve seen it somewhere.
You can run the django-admin testserver mydata.json
command to spin up a testing server with data from a provided fixture. The way it was done in the example I saw was by making a custom Django command where instead of static fixture the testserver’s database was populated dynamically by factories. I don’t remember the details how it was implemented, though.
After the testserver was ready, the Cypress tests were run. Backend and the frontend were wired by npm’s start-server-and-test
package.
Application with similar setup can be checked out here. Especially note the custom testserver command as well as the cypress commands.
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install json-server
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.
Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesExplore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits
Save this library and start creating your kit
Share this Page