![]() |
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 Approach
Steps to create a REST API with JSON ServerRun the below command to Create a package.json file: npm init -y Run the below command to Install the JSON Server globally using npm: npm i -g json-server Run the below command to Install Axios: npm install axios Project Structure: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.json GET Request Returns a List of all UsersExample: 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.js Output: Ashish, Regmi, [email protected]
Anshu, abc, [email protected]
Shreya, def, [email protected]
John, aaa, [email protected]
Geeks For, Geeks, [email protected] POST Request to create a New UserExample: 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.js Output: {
"first_name": "Geeks For",
"last_name": "Geeks",
"email": "[email protected]",
"id": "5"
} PUT Request to Update an Existing UserExample: 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.js Output: {
first_name: 'Geeks For',
last_name: 'Geeks',
email: '[email protected]',
id: '5'
} Above data is modified as {
first_name: 'Geeks For',
last_name: 'Geeks',
email: '[email protected]',
id: '5'
} DELETE Request to Delete a UserExample: 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.js Output: {
id: '3',
first_name: 'Shreya',
last_name: 'def',
email: '[email protected]'
} |
Reffered: https://www.geeksforgeeks.org
Web Technologies |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |