Photo by Afif Kusuma on Unsplash
Create a fake REST API with zero coding in less than 30 seconds(seriously)
You may want to create a fully functional frontend but for some reason, you're lacking a backend or API to service it. Maybe because you can't develop one or you're just practicing or focusing on the front end or you're probably lazy 😁.
JSON Server
Worry no more, JSON Server allows you to create a full fake REST API with almost no code at all, so you can rest more or spend your time on other stuff 😜, this is how you can use JSON Server.
Getting Started
To use JSON Server, you must have nodejs installed, you can install nodejs from here.
Now, in your terminal or command prompt
Install JSON Server
npm install -g json-server
- npm is a node package manager
- g means global so that you can be able to access it in any other folder
Create a db.json with some data
{
users: [
{"id": "1", "name": "juma", "number": 1900708915}
],
computers: [
{"id": 1, "name": "LATITUDE E5410", "details": "Windows 11, intel CORE i5" }
]
}
Start JSON Server
json-server --watch db.json
Now if you go to localhost:3000/users, you'll get
[
{"id": "1", "name": "juma", "number": 1900708915}
]
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 without making changes to the data.
For more details on routing, refer to this section of the documentation.
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. This would allow us to use JSON Server in a real nodejs application with more advanced applications
Here's how to
// server.js
const jsonServer = require('json-server')
const server = jsonServer.create()
const path = require('path')
const router = jsonServer.router(path.join(__dirname, 'db.json'))
const middlewares = jsonServer.defaults()
server.use(middlewares)
server.use(router)
server.listen(3000, () => {
console.log('JSON Server is running')
})
Now if you run
node server.js
Everything should be as before
For more details on this and how to build custom routes and route access control, refer to this section of the documentation.
This article doesn't discuss JSON Server to the fullest extent but what is shared is enough to get you started with JSON Server, and I hope you find this useful for your next project.
Follow so you don't miss out on useful content like this, Happy Hacking 😀