INTRODUCTION:
REST APIs power many modern web applications by enabling seamless data exchange between clients and servers. In this tutorial, we'll build a basic REST API using Node.js and Express, and we'll store data in MongoDB.
By the end, you will have a fully functional API that supports CRUD (Create, Read, Update, Delete) operations.
*** Step 1: Setting Up the Project
Install Node.js
using node -v;Initialize a New Node.js Project
Create a new project directory and initialize a package.json file;
mkdir node-rest-api && cd node-rest-api
npm init -y;
3.Install Required Dependencies
express - for building the API
mongoose - to interact with MongoDB
dotenv - to manage environment variables
cors - to handle cross-origin requests
using this command:
npm install express mongoose dotenv cors;
*** Step 2: Create the Express Server
Create a file named server.js and set up a basic Express server
const express = require("express");
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const cors = require("cors");
dotenv.config();
const app = express();
// Middleware
app.use(express.json()); // Parse JSON requests
app.use(cors()); // Enable CORS
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(Server running on port ${PORT}
);
});
Now, run the server:
node server.js
you should see like this:
Server running on port 5000
*** Step 3: Connect to MongoDB
- Set Up MongoDB If you don’t have MongoDB installed, use MongoDB Atlas (a free cloud database).
Go to MongoDB Atlas and create a free cluster.
Get the connection string (replace and ).
- Update .env File Create a .env file in the project root and add: MONGO_URI=mongodb+srv://:@cluster.mongodb.net/myDatabase; Modify server.js to Connect to MongoDB: mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true, }) .then(() => console.log("MongoDB Connected")) .catch((err) => console.error(err));
restart the server:
node server.js;
you should see like this:
MongoDB Connected
Server running on port 5000
**** Step 4: Create a Model and Routes
- Define a Model (Schema) Create a models/Task.js file: const mongoose = require("mongoose");
const TaskSchema = new mongoose.Schema({
title: String,
completed: {
type: Boolean,
default: false,
},
});
module.exports = mongoose.model("Task", TaskSchema);
Set Up API Routes
Create a routes/tasks.js file:
const express = require("express");
const Task = require("../models/Task");
const router = express.Router();
// Create a new task
router.post("/", async (req, res) => {
try {
const task = new Task(req.body);
await task.save();
res.status(201).json(task);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// Get all tasks
router.get("/", async (req, res) => {
try {
const tasks = await Task.find();
res.json(tasks);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Update a task
router.put("/:id", async (req, res) => {
try {
const task = await Task.findByIdAndUpdate(req.params.id, req.body, { new: true });
res.json(task);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// Delete a task
router.delete("/:id", async (req, res) => {
try {
await Task.findByIdAndDelete(req.params.id);
res.json({ message: "Task deleted" });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
*** Step 5: Test the API with Postman
Start the server:
node server.js
Use Postman or cURL to test API endpoints:
** Create a Task (POST)
POST http://localhost:5000/api/tasks
Content-Type: application/json
{
"title": "Learn Node.js"
}
** Get All Tasks (GET)
GET http://localhost:5000/api/tasks
**Update a Task (PUT)
PUT http://localhost:5000/api/tasks/
Content-Type: application/json
{
"completed": true
}
**Delete a Task (DELETE)
DELETE http://localhost:5000/api/tasks/
*** Step 6: Deploy the API (Optional)
To make the API live, deploy it to Render, Vercel, or Railway.
Push your code to GitHub.
Deploy using your preferred platform.
conclusion:
Congratulations! 🎉 You just built a REST API using Node.js, Express, and MongoDB. This is the foundation for creating powerful backend applications.
Next Steps
Add JWT authentication.
Implement pagination and search.
Create a frontend using React/Vue.