Sometimes you need to create or mock up an API that you can play and test while developing your application. The data does not need to be fake, but whatever you wish, and the JSON Server gives you the possibility to quickly create, read, update, and delete.
Let’s start by creating a new repository over at GitHub and adding only the README file. On your setup, navigate to the folder where you want to clone the repo, and clone it.
In your terminal type:
git init
then:
git clone https://github.com/ifkas/restful-api-vercel.git
Replace https://github.com/ifkas/restful-api-vercel.git
with the URL of your repository. Open the cloned folder, there you will see only the README file you previously created.
Now, time to create the “database” file, create a new file and name it as you wish, for example, name it db.json or data.json and fill it with your data (JSON). Something like:
{
"posts": [
{
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
},
{
"id": 3,
"title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
"body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
}
]
}
Let’s install the JSON Server, in the terminal type:
npm install -g json-server
Note: the-g
command means to install it globally on your computer, you can omit it if needed.
If you need to create custom routes, then you need to add a server.js file where the default middleware exists, add your own custom routes and listen to a port. I’ve added explanatory comments in the snippet below.
// JSON Server module
const jsonServer = require("json-server");
const server = jsonServer.create();
const router = jsonServer.router("db/db.json");
// Make sure to use the default middleware
const middlewares = jsonServer.defaults();
server.use(middlewares);
// Add this before server.use(router)
server.use(
// Add custom route here if needed
jsonServer.rewriter({
"/api/*": "/$1",
})
);
server.use(router);
// Listen to port
server.listen(3000, () => {
console.log("JSON Server is running");
});
// Export the Server API
module.exports = server;
You can read more about the modules here: https://github.com/typicode/json-server#module
Let’s start and run the server with this command:
json-server --watch db.json
Done, the database is created.
In the terminal, you will see printed URLs where you can test if the server is up and running, also you can check the posts endpoint too if all is good it will open the JSON in your browser.
Tip: if you are using the Chrome browser you can use this addon to prettify or properly parse the data in JSON format and be easily readable: JSON Formatter.
Note: you can change the “posts” name of the resource to anything you wish, in the db.json file simply rename the object name and it will automatically route to that path.
Vercel
To deploy it to Vercel you need to create a configuration file and make sure to name it vercel.json, save the file inside the root of your project folder and paste this code inside:
{
"version": 2,
"builds": [
{
"src": "server.js",
"use": "@vercel/node",
"config": {
"includeFiles": ["db.json"]
}
}
],
"routes": [
{
"src": "/(.*)",
"dest": "server.js"
}
]
}
in the snippet above make sure to include the db.json file or whatever you name it.
More information: https://vercel.com/docs/project-configuration
Commit and push the changes on GitHub.
Next, log in to Vercel, click Add a new project, then import the repository, leave everything as it is, maybe just rename the project as you wish, and click Deploy.
That’s it, congratulations, your new JSON Server is ready, up and running.
Let’s test, open the console in the browser, and paste this:
fetch('WRITE HERE THE ENDPOINT URL')
.then(response => response.json())
.then(data => console.log(data));
Replace the endpoint URL with your own and if all is good you should get a response back in the console.
For more versatile testing with the available methods, you can use Insomnia or Postman.
Useful notes:
You can make GET, POST, PUT and DELETE requests to it. Or hit individual ID for example http://yoururl.com/api/1 where 1 is the ID of the individual item.
Useful links:
What is RESTful API: https://aws.amazon.com/what-is/restful-api
What is JSON Server: https://www.npmjs.com/package/json-server
Repo template: https://github.com/ifkas/restful-api-vercel.git
Have fun and enjoy!
Let’s connect via Twitter: https://twitter.com/ifkas