This content originally appeared on DEV Community and was authored by Pablo Veiga
Depending on how your team works, you might need to move forward with the front end while the back end is still being structured.
Or perhaps you need speed to create an MVP or a proof of concept.
This means that you probably will receive interface designs from the designer or product manager and will need to implement them using mocked data, while the back end is still not ready.
When I first started developing web applications, I used to mock data within the components by replicating pieces of HTML or setting variables with mocked arrays or objects according to what the interface required.
The problem is when you do this, you increase the amount of work needed when the integration time comes because you will need to:
- remove mocked data from components;
- create the services which connect the front end to the back end;
- consume these services to display real data;
It turns out that this path can be much less painful if you use mock API's.
TL;DR
In this article I show you how to easily mock a simple REST API using JSON Server
JSON Server is just one option amongst several others that allow you to fake REST APIs to deal with interface prototyping.
JSON Server - Mock REST API
Let's start with JSON Server. This package allows you to bootstrap a mocked REST API server without much effort.
Considering you have already created the main structure of your project using NPM or Yarn, install the package to your project using one of the following commands:
// If using NPM
npm install json-server --save-dev
// If using Yarn
yarn add json-server -D
Then, you need to follow these three steps:
- Configure an entry-point file;
- Create a JSON file with mocked data;
-
Add a new script to your
package.json
file;
1. Configuring an entry-point file
JSON Server will act like a simplified Express server, so, this is how you create the main file required by it to run:
const path = require('path')
const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router(path.join(__dirname, 'db.json'))
const middlewares = jsonServer.defaults()
server.use(
jsonServer.rewriter({
'/api/*': '/$1'
})
)
server.use(middlewares)
server.use(jsonServer.bodyParser)
server.use(router)
server.listen(3000, () => {
console.log('JSON Server is running')
})
Notice that here, I intend to use the prefix /api
for my requests. You may change it to whatever you like.
2. Creating mocked data
JSON Server works based on Low DB a "Tiny local JSON database for small projects". So you need to configure a db.json
file that will serve the data.
Let's suppose I need to list users
and products
, for example. This is how our JSON file will be:
{
"users": [
{
"id": 1,
"name": "Jon Doe",
"age": 30,
"active": true
},
{
"id": 2,
"name": "Jane Doe",
"age": 25,
"active": true
},
{
"id": 3,
"name": "Bob Taylor",
"age": 45,
"active": false
}
],
"products": [
{
"id": 1,
"name": "Pizza",
"price": 10,
"active": true
},
{
"id": 2,
"name": "Hamburger",
"price": 7,
"active": true
},
{
"id": 3,
"name": "Ice Cream",
"price": 2.5,
"active": false
}
]
}
This is enough for the mock API to be started and for you to make requests right away.
But first, let's create a new script into the package.json
file so that we don't need to install json-server
globally in your machine.
3. Creating the mock API script:
Add the following property to the scripts
section of the package.json
file:
"mock:api": "node json-server/server"
And that's it. In this implementation, we configured JSON server to bootstrap the mock API using the port 3000 but you might change it in the server.js
file.
This is an example of the results when requesting http://localhost:3000/api/users
directly from the browser.
I'm using the JSON Viewer extension to display the data properly formatted and coloured as seen above.
4. JSON Server basic operations
JSON Server will let you implement front-end services that make real API calls and let them ready to wait for the real back-end API because it works exactly like a REST API.
This also means you can use the most common verbs to perform actions with your data:
-
GET
: used to retrieve full arrays, objects by id or even filter by certain attributes:
GET: /users => retrieves all users
GET: /users/1 => retrieve the user with id = 1
GET: /users?_sort=age&_order=desc => retrieve users sorted by age descending
GET: /users?age_gte=10 => retrieve users whose ages are greater than 10
-
POST
- used to create new values. Make aPOST
request using the URL of the resource you want to add and pass the value using the body.
// This will add a new product to the "products" array
URL: `/api/products`
BODY:
{
"id": 4,
"name": "Chocolate",
"price": 6,
"active": true
}
-
PUT
- used to update a resource. Make aPUT
request passing the id of the resource you want to update as a query param and the value to be set using the body.
// This will update the user with the id = 2
URL: `/api/users/2`
BODY:
{
"id": 2,
"active": false
}
DELETE
- used to remove a resource. Make a DELETE
request passing the id of the resource you want to be deleted as a query param.
This will remove the user with id = 3
DELETE: `/api/users/3`
5. JSON Server advanced operations
As JSON server works just like Express JS, you can also extend it to perform more advanced operations, map different URL's to specific data in the db.json
file or even implement middlewares and _ parsers_.
I'm not going to dive deep into all of the possibilities because they are endless. It's worth taking a look at the full documentation in their Github to take advantage of its full power.
Conclusions
You don't need to install and configure databases and back-end API anymore when starting a new front-end project. Sometimes all you need is some sample data to simulate real scenarios.
In this article you were introduced to JSON Server, an extraordinary tool that can help you bootstrap a simple (or not so simple) REST API very quickly that will provide support for your next front-end prototyped application.
You can find a fully-working example in this repository.
I hope you liked it.
Please, share and comment!
Cover image by Marc-Olivier Jodoin
This content originally appeared on DEV Community and was authored by Pablo Veiga
Pablo Veiga | Sciencx (2021-07-17T16:19:31+00:00) JS – Mocking a REST API with JSON Server. Retrieved from https://www.scien.cx/2021/07/17/js-mocking-a-rest-api-with-json-server/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.