Introduction
REST APIs are the backbone of modern web applications. In this tutorial, we will build a complete REST API using Node.js and Express.js.
Prerequisites
- Node.js 18+ installed
- Basic JavaScript knowledge
- Postman or similar API testing tool
Step 1: Project Setup
mkdir my-api && cd my-api
npm init -y
npm install express cors helmet morgan
Step 2: Create Server
const express = require("express");
const cors = require("cors");
const helmet = require("helmet");
const morgan = require("morgan");
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(cors());
app.use(helmet());
app.use(morgan("dev"));
app.use(express.json());
// Routes
app.get("/api/health", (req, res) => {
res.json({ status: "OK", timestamp: new Date() });
});
app.listen(PORT, () => {
console.log();
});
Step 3: Add Database
We will use MongoDB with Mongoose for data persistence:
const mongoose = require("mongoose");
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGO_URI);
console.log("MongoDB connected");
} catch (error) {
console.error("Error:", error.message);
process.exit(1);
}
};
connectDB();
Conclusion
You now have a basic REST API structure. Next steps include adding authentication, validation, and error handling.