Crafting High-Performance RESTful APIs with ExpressJS
Last Updated :
21 Aug, 2024
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:
Approach
- Start 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.js
Step 1: Setting Up the Project
- Initialize the Project: Run npm init to create a package.json file on your terminal.
MKDIR RESTFUL
cd RESTFUL
npm init
- Install Dependencies: Install Express and other necessary packages using npm install express.
npm install express mongoose
Updated 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 Postman
1. 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 request- Click “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.js
Output:
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
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
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