REST API CRUD Operations Using ExpressJS
Last Updated :
19 Feb, 2025
In modern web development, REST APIs enable seamless communication between different applications. Whether it’s a web app fetching user data or a mobile app updating profile information, REST APIs provide these interactions using standard HTTP methods.
What is a REST API?
A REST API (Representational State Transfer Application Programming Interface) is an architectural style that defines a set of constraints for creating web services. It allows different software systems to communicate over HTTP, using standard HTTP methods (GET, POST, PUT, DELETE).
- Create: Add new resources to the system (HTTP POST)
- Read: Retrieve items (HTTP GET)
- Update: Modify existing items (HTTP PUT/PATCH)
- Delete: Remove items (HTTP DELETE)
HTTP Methods
In HTTP, various methods define the desired action to be performed on a resource identified by a URL. Here's a concise overview of some common HTTP methods:
GET:
- Meaning: The GET method is used to request data from a specified resource.
- Purpose: It is used to retrieve information from the server without making any changes to the server's data. GET requests should be idempotent, meaning multiple identical GET requests should have the same effect as a single request.
- Example: When you enter a URL in your web browser's address bar and press Enter, a GET request is sent to the server to retrieve the web page's content.
POST:
- Meaning: The POST method is used to submit data to be processed to a specified resource.
- Purpose: It is typically used for creating new resources on the server or updating existing resources. POST requests may result in changes to the server's data.
- Example: When you submit a form on a web page, the data entered in the form fields is sent to the server using a POST request.
PUT:
- Meaning: The PUT method is used to update a resource or create a new resource if it does not exist at a specified URL.
- Purpose: It is used for updating or replacing the entire resource at the given URL with the new data provided in the request. PUT requests are idempotent.
- Example: An application might use a PUT request to update a user's profile information.
PATCH:
- Meaning: The PATCH method is used to apply partial modifications to a resource.
- Purpose: It is used when you want to update specific fields or properties of a resource without affecting the entire resource. It is often used for making partial updates to existing data.
- Example: You might use a PATCH request to change the description of a product in an e-commerce system without altering other product details.
DELETE:
- Meaning: The DELETE method is used to request the removal of a resource at a specified URL.
- Purpose: It is used to delete or remove a resource from the server. After a successful DELETE request, the resource should no longer exist.
- Example: When you click a "Delete" button in a web application to remove a post or a file, a DELETE request is sent to the server.
They are an essential part of the RESTful architecture, which is commonly used for designing web APIs and web services.
Implementing the CRUD operations
Install Express
npm install express
We’ll also install body-parser to parse incoming request bodies (for POST and PUT requests):
npm install body-parser
Setting Up the Basic Server
In the project folder, create a file called app.js. This file will contain the code to set up the basic Express server.
JavaScript
// app.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
let items = [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' }
];
app.get('/', (req, res) => {
res.send('Welcome to the REST API!');
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
The express server has been created and it is running on the
http://localhost:3000/
In the above example
- This code creates a server using Express and allows it to read JSON data in requests.
- It uses a simple list of items to simulate a database.
- app.get('/', (req, res) => { ... }); defines a route that listens for GET requests on the root URL (/).
- When a client makes a GET request to the root URL (http://localhost:3000/), the callback function inside app.get is triggered.
- The server responds with the message 'Welcome to the REST API!' using res.send().
Now, we will perform the CRUD operations.
POST(Create)
It can be used for adding the new item in the database.
JavaScript
// Create (POST): Add a new item
app.post('/items', (req, res) => {
const { name } = req.body;
const newItem = { id: items.length + 1, name };
items.push(newItem);
res.status(201).json(newItem);
});
POST RequestThe new item name: New Item has been added in the database.
GET (Read)
We need two routes: One to retrieve all items, and another to retrieve an individual item by its ID.
JavaScript
// Read (GET): Get all items
app.get('/items', (req, res) => {
res.json(items);
});
// Read (GET): Get a single item by ID
app.get('/items/:id', (req, res) => {
const item = items.find(i => i.id === parseInt(req.params.id));
if (!item) return res.status(404).send('Item not found');
res.json(item);
});
List of all the items we are getting by using
http://localhost:3000/items
Output
GET All RequestIf we want to get the specific element
http://localhost:3000/items/2
Output:
GET Specific RequestUpdate (PUT/PATCH)
We’ll add a route to update an item’s name using a PUT request.
JavaScript
// Update (PUT): Update an item by ID
app.put('/items/:id', (req, res) => {
const item = items.find(i => i.id === parseInt(req.params.id));
if (!item) return res.status(404).send('Item not found');
item.name = req.body.name; // Update the item's name
res.json(item);
});
Output
PUT RequestDELETE(Delete)
We will add a route to delete an item using a DELETE request.
JavaScript
// Delete (DELETE): Delete an item by ID
app.delete('/items/:id', (req, res) => {
const itemIndex = items.findIndex(i => i.id === parseInt(req.params.id));
if (itemIndex === -1) return res.status(404).send('Item not found');
const deletedItem = items.splice(itemIndex, 1);
res.json(deletedItem);
});
In this example I am trying to delete the item which is not present. So it is showing the 404 not found.
Deleting An ItemFull Working Example
Here’s the full code for the Express CRUD API:
JavaScript
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
let items = [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' }
];
// Create (POST): Add a new item
app.post('/items', (req, res) => {
const { name } = req.body;
const newItem = { id: items.length + 1, name };
items.push(newItem);
res.status(201).json(newItem);
});
// Read (GET): Get all items
app.get('/items', (req, res) => {
res.json(items);
});
// Read (GET): Get a single item by ID
app.get('/items/:id', (req, res) => {
const item = items.find(i => i.id === parseInt(req.params.id));
if (!item) return res.status(404).send('Item not found');
res.json(item);
});
// Update (PUT): Update an item by ID
app.put('/items/:id', (req, res) => {
const item = items.find(i => i.id === parseInt(req.params.id));
if (!item) return res.status(404).send('Item not found');
item.name = req.body.name;
res.json(item);
});
// Delete (DELETE): Delete an item by ID
app.delete('/items/:id', (req, res) => {
const itemIndex = items.findIndex(i => i.id === parseInt(req.params.id));
if (itemIndex === -1) return res.status(404).send('Item not found');
const deletedItem = items.splice(itemIndex, 1);
res.json(deletedItem);
});
// Start the server
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
Best Practices for Creating a REST API Using Express.js
- Use Proper HTTP Methods: Follow RESTful conventions by using GET for retrieving data, POST for creating data, PUT/PATCH for updating data, and DELETE for removing data.
- Implement Middleware: Use middleware like express.json() to parse incoming JSON requests and morgan for logging API requests.
- Validate Input Data: Ensure data integrity by using validation libraries like Joi or express-validator before processing requests.
- Use Meaningful Route Names: Design clear, resource-oriented URLs (e.g., /students/:id instead of /getStudent).
Similar Reads
Travel Planning App API using Node & Express.js In this article, weâll walk through the step-by-step process of creating a Travel Planning App With Node and ExpressJS. This application will provide users with the ability to plan their trips by searching for destinations, booking flights and hotels, submitting reviews, receiving notifications, sha
10 min read
How to create routes using Express and Postman? In this article we are going to implement different HTTP routes using Express JS and Postman. Server side routes are different endpoints of a application that are used to exchange data from client side to server side.Express.js is a framework that works on top of Node.js server to simplify its APIs
3 min read
Creating a REST API Backend using Node.js, Express and Postgres Creating a REST API backend with Node.js, Express, and PostgreSQL offers a powerful, scalable solution for server-side development. It enables efficient data management and seamless integration with modern web applications.This backend can do Query operations on the PostgreSQL database and provide t
4 min read
Crafting High-Performance RESTful APIs with ExpressJS Building RESTful APIs with Express.js involves setting up a Node.js server using Express, defining routes to handle various HTTP methods (GET, POST, PUT, DELETE), and managing requests and responses with middleware. You can integrate a database like MongoDB for data persistence and implement error h
4 min read
How to use TypeScript to build Node.js API with Express ? TypeScript is a powerful version of JavaScript that incorporates static typing and other features, making it easy to build and maintain large applications. Combined with Node.js and Express, TypeScript can enhance your development experience by providing better type safety and tools. This guide will
4 min read
How to Build a RESTful API Using Node, Express, and MongoDB ? This article guides developers through the process of creating a RESTful API using Node.js, Express.js, and MongoDB. It covers setting up the environment, defining routes, implementing CRUD operations, and integrating with MongoDB for data storage, providing a comprehensive introduction to building
6 min read