Photo by Jacob Miller on Unsplash
How To Create and Deploy a json-server
A short step by step by step guide to creating a JSON-DB server and deploying it on cyclic.sh
json-server
is a tool for creating mock REST API fast! To get started, ensure you have the following requirements:
- NodeJS (npm)
Let's get started!
On an empty folder, initiate a nodejs application by running the following on your terminal/CMD:
npm init -y
Once that is complete, you install the following packages:
json-server
json-serve
cors
nodemon
(as a dev dependency)
npm install json-server json-serve cors
npm install -D nodemon
After the installation, create a new file: index.js
. This is the entry point for the json-serve. Add the following inside the file:
const jsonServer = require('json-server')
const cors = require('cors')
const path = require('path')
const server = jsonServer.create()
const router = jsonServer.router(path.join(__dirname, 'db.json'))
const middlewares = jsonServer.defaults()
server.use(cors())
server.use(jsonServer.bodyParser)
server.use(middlewares)
server.use(router)
const PORT = 8000
server.listen(PORT, () => {
console.log(`JSON Server is running on http://localhost:${PORT}`)
})
In the code above, a server has been created that will be fetching and updating data from a json file, db.json
In the project root, create a new file: db.json
and add the following:
{
"feedback": [
{
"id": 1,
"rating": 10,
"user_name": "Tony Stark",
"text": "You are the ironman of this world"
},
{
"id": 2,
"rating": 9,
"user_name": "Bruce Wayne",
"text": "You are the batman of this world"
},
{
"id": 3,
"rating": 8,
"user_name": "Peter Parker",
"text": "You are the spiderman of this world"
}
]
}
The mock server is ready to run, but let's add some scripts in package.json
:
Update the "scripts"
to:
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
},
To run the server, use either of the scripts:
npm run start
The server runs on port 8000:
The API endpoint is: http://localhost:8000/feedback
The following images show the GET and POST methods:
GET
POST
After POST.ing new data, the db.json
files update the latest entry.
Deploying to cyclic.sh
Create an account at cyclic.sh (link account to your GitHub profile). Then upload the mock server to GitHub.
To deploy on cyclic, click the green deploy button on the dashboard:
Select the Link Your Own
tab to select from GitHub:
Search for the repo and click connect:
After a successful deployment:
Just like that you have your simple server/API ready for use!