Crafting High-Performance RESTful APIs with ExpressJS Last Updated : 21 Aug, 2024 Comments Improve Suggest changes Like Article Like Report 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 handling, authentication, and security measures as needed. Finally, deploy the API to a cloud platform like Heroku or AWS for production use.Crafting High-Performance RESTful APIs with ExpressJSPrerequisites:ExpressJsNodeJsJavascriptApproachStart by importing Express in your index.js. Initialize the Express app using const app = express();.Set a port for the server to listen on, e.g., const PORT = 3000;.Use app.get(), app.post(), app.put(), app.delete() to define routes for various HTTP methods.Capture dynamic parameters in routes using :param, e.g., app.get('/user/:id', (req, res) => {...}).Access query parameters using req.query, e.g., req.query.name. Use middleware like app.use(express.json()) to parse incoming JSON requests.Send responses using res.send(), res.json(), or res.status() to set HTTP status codes.Steps to Create RESTful APIs with Express.jsStep 1: Setting Up the ProjectInitialize the Project: Run npm init to create a package.json file on your terminal.MKDIR RESTFULcd RESTFULnpm initInstall Dependencies: Install Express and other necessary packages using npm install express.npm install express mongooseUpdated Dependencies"dependencies": { "express": "^4.19.2", "mongoose": "^8.5.2" }Project Structure:Project StructureExample: This example shows the creation of RESTful API. JavaScript // index.js const express = require("express"); const connectDB = require("./db"); const mongoose = require("mongoose"); const app = express(); const PORT = process.env.PORT || 3000; // Connect to MongoDB connectDB(); // Create a User schema and model const UserSchema = new mongoose.Schema({ name: { type: String, required: true }, id: { type: Number, required: true } }); const User = mongoose.model("User", UserSchema); app.use(express.json()); app.get("/", async (req, res) => { const users = await User.find(); res.json(users); }); app.get("/api/users/:id", async (req, res) => { const user = await User.findById(req.params.id); if (!user) return res.status(404).send("User not found"); res.json(user); }); app.post("/api/users", async (req, res) => { const newUser = new User({ name: req.body.name, id: req.body.id }); await newUser.save(); res.status(201).json(newUser); }); app.put("/api/users/:id", async (req, res) => { const user = await User.findById(req.params.id); if (!user) return res.status(404).send("User not found"); user.name = req.body.name; await user.save(); res.json(user) }); app.delete("/api/users/:id", async (req, res) => { const user = await User.findById(req.params.id); console.log(user) if (!user) return res.status(404).send("User not found"); await User.deleteOne({ _id: req.params.id }); res.json(user) }); app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); }); JavaScript // db.js const mongoose = require("mongoose"); const connectDB = async () => { try { await mongoose.connect( process.env.MONGO_URI || "mongodb://localhost:27017/Exp"); console.log("MongoDB connected"); } catch (err) { console.error(err.message); process.exit(1); } }; module.exports = connectDB; Output:Data in MongoDBSteps to Test the API using Postman1. POST Request:Make the request type to POST .Enter http://localhost:3000/api/users in the request URL.The “Body” tab can be selected, and under the “Data format”, choose “Raw” that can be “JSON”.Add the following JSON data:{ "name":"John", "id":3}POST requestClick “Send. “Post this you should see a success message and the new user should be stored in the database.2. DELETE Request:Modify the request type to delete.Enter http://localhost:3000/api/users/user_id of the user to the request URL (provided there is a user with such ID).Click “Send. “You should be seeing a success message and in the database, the user will be deleted.DELETE Request3. PUT Request:Alters the request type to PUT.Enter http://localhost:3000/api/users/user_id in the request URL.In the “Body” tab, add the updated JSON data:{"name": "John Deo"}Click “Send. “There should be a success message and after that, the user information will be modified in the database.PUT Request4. GET Request:Open Postman.Specify the request type to Get.Enter http://localhost:3000 at the end of the request URL.Click “Send. “Looking at the JSON response, you should be able to get all the users currently in the database.GET RequestSteps to Run Project:Navigate inside the folder RESTFUl and enter the following command to start the project:node index.jsOutput: Comment More infoAdvertise with us Next Article Crafting High-Performance RESTful APIs with ExpressJS B bishalmandal235 Follow Improve Article Tags : GBlog Web Technologies Node.js Express.js Web-Tech Blogs +1 More Similar Reads Explain the concept of RESTful APIs in Express. RESTful APIs are a popular way of creating web applications that exchange data over the internet in a standardized manner. These APIs follow specific principles such as using resource-based URLs and HTTP methods to perform various operations like creating, reading, updating, and deleting data. Expre 3 min read REST API CRUD Operations Using ExpressJS 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 7 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 Optimizing Your MERN Stack Application Performance The MERN stack, comprising MongoDB, Express.js, React.js, and Node.js, is a popular choice for developing modern web applications. However, like any technology stack, optimizing performance is crucial to ensure a responsive and efficient user experience. This article delves into strategies and best 3 min read Build a document generator with Express using REST API In the digital age, the need for dynamic and automated document generation has become increasingly prevalent. Whether you're creating reports, invoices, or any other type of document, having a reliable system in place can streamline your workflow. In this article, we'll explore how to build a Docume 2 min read Document Management System with React and Express.js This project is a Document Management System (DMS) developed with a combination of NodeJS, ExpressJS for the server side and React for the client side. The system allows users to view, add, and filter documents. The server provides a basic API to retrieve document data, while the React application o 7 min read Creating Socket.IO Server using Express Generator Socket.IO is a library for real-time communication between the server and the client. In Socket.IO, the headers are shared only once and it also works on the top of the TCP layer. Web Sockets are the base of the Socket.IO library. It is easier to implement the Socket.IO in express applications that 3 min read How to Structure my Application in Express.js ? A clean and well-organized folder structure is crucial for building maintainable and scalable Express.js applications. This article explores best practices for structuring your application, organizing components, and maintaining a modular architecture.Why Structure an Express Application?A well-stru 6 min read What Are Some Common Performance Bottlenecks in React-Redux Applications? React-Redux applications are powerful for building complex and scalable web applications. However, as applications grow in size and complexity, performance optimization becomes important to ensure smooth user experiences. Common Performance Bottlenecks in React-Redux ApplicationsIdentifying and addr 4 min read Like