A complete REST API with CRUD operations and best practices (and zero Googling, I swear 😄)
🧠 What’s Inside:
- REST API basics for beginners
- Full CRUD (Create, Read, Update, Delete) with Express.js
- Clean code and best practices
- Simple in-memory data storage (no DB required yet)
🚀 What is a REST API?
A REST API allows you to communicate with your backend via HTTP methods:
HTTP Method | Action | Description |
---|---|---|
GET | Read | Fetch data from the server |
POST | Create | Add new data |
PUT | Update | Update existing data |
DELETE | Delete | Remove data from the server |
📁 Folder Structure
We’re keeping things simple here:
rest-api/
├── index.js
├── data.js # in-memory storage (mock DB)
└── routes/
└── tasks.js # all task routes
⚙️ Step 1: Setup Your Project
mkdir rest-api
cd rest-api
npm init -y
npm install express
🧩 Step 2: Create In-Memory Storage
data.js
let tasks = [
{ id: 1, title: "Learn Node.js" },
{ id: 2, title: "Build an API" }
];
module.exports = tasks;
🛣️ Step 3: Create Routes
routes/tasks.js
const express = require('express');
const router = express.Router();
let tasks = require('../data');
// GET all tasks
router.get('/', (req, res) => {
res.json(tasks);
});
// GET task by ID
router.get('/:id', (req, res) => {
const task = tasks.find(t => t.id === parseInt(req.params.id));
task ? res.json(task) : res.status(404).json({ error: 'Not found' });
});
// POST a new task
router.post('/', (req, res) => {
const { title } = req.body;
const newTask = { id: tasks.length + 1, title };
tasks.push(newTask);
res.status(201).json(newTask);
});
// PUT (update) task
router.put('/:id', (req, res) => {
const task = tasks.find(t => t.id === parseInt(req.params.id));
if (!task) return res.status(404).json({ error: 'Not found' });
task.title = req.body.title;
res.json(task);
});
// DELETE task
router.delete('/:id', (req, res) => {
tasks = tasks.filter(t => t.id !== parseInt(req.params.id));
res.status(204).send();
});
module.exports = router;
🧠 Step 4: Wire It All Together
index.js
const express = require('express');
const app = express();
const taskRoutes = require('./routes/tasks');
const PORT = 3000;
// Middleware to parse JSON
app.use(express.json());
// Task routes
app.use('/api/tasks', taskRoutes);
// Home route
app.get('/', (req, res) => {
res.send('📡 Welcome to your REST API!');
});
// Start server
app.listen(PORT, () => {
console.log(`🚀 Server running at http://localhost:${PORT}`);
});
🔬 Step 5: Test It!
Use Postman, Insomnia, or browser to test:
➕ Create Task
POST /api/tasks
{ "title": "Write a blog post" }
📥 Get All Tasks
GET /api/tasks
🔍 Get Single Task
GET /api/tasks/1
🔁 Update Task
PUT /api/tasks/1
{ "title": "Master Node.js" }
❌ Delete Task
DELETE /api/tasks/1
✅ Best Practices You Followed
- ✅ Modular route handling
- ✅ Separation of logic and data
- ✅ Used proper status codes
- ✅ Middleware for JSON parsing
- ✅ Clean, readable structure