![]() |
VOOZH | about |
Setting up a RESTful API using JSON Server, a lightweight and easy-to-use tool for quickly prototyping and mocking APIs. JSON Server allows you to create a fully functional REST API with CRUD operations (Create, Read, Update, Delete) using a simple JSON file as a data source.
Table of Content
Run the below command to Create a package.json file:
npm init -yRun the below command to Install the JSON Server globally using npm:
npm i -g json-serverRun the below command to Install Axios:
npm install axios👁 Screenshot-2024-05-04-145653
Example: The example below shows the JSON file that represents your data model.
Run the below command to start JSON Server and point it to your JSON file:
npm json-server --watch users.jsonExample: In this example the endpoint returns a list of all users stored on the server. Each user object contains properties such as id, name, and email.
Run the below command to test the GET request:
node get_request.jsOutput:
Ashish, Regmi, ashish@gmail.com
Anshu, abc, anshu@gmail.com
Shreya, def, shreya@gmail.com
John, aaa, John@yahoo.com
Geeks For, Geeks, gfg@gmail.comExample: In this example, Send a POST request to create a new user will create a new user with the provided data.
Run the below command to test the POST Request:
node post_request.jsOutput:
{
"first_name": "Geeks For",
"last_name": "Geeks",
"email": "gfg@yahoo.com",
"id": "5"
}Example: In this example, send a PUT request to update an existing user this will update the user with the provided data.
Run the below command to test the PUT Request:
node put_request.jsOutput:
{
first_name: 'Geeks For',
last_name: 'Geeks',
email: 'gfg@yahoo.com',
id: '5'
}Above data is modified as
{
first_name: 'Geeks For',
last_name: 'Geeks',
email: 'gfgofficial@gmail.com',
id: '5'
}Example: In this example the endpoint deletes the user with the specified id from the server. After deletion, the user will no longer exist in the database.
Run the below command to test the PUT Request:
node delete_request.jsOutput:
{
id: '3',
first_name: 'Shreya',
last_name: 'def',
email: 'shreya@gmail.com'
}