Crafting High-Performance RESTful APIs with ExpressJS
Last Updated :
21 Aug, 2024
Improve
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.

Prerequisites:
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:

Example: This example shows the creation of RESTful API.
// 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}`);
});
// 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:

Steps 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
}

- 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.

3. 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.

4. 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.

Steps to Run Project:
Navigate inside the folder RESTFUl and enter the following command to start the project:
node index.js
Output: