๐ REST APIs & Routing in Express
Now you move from basic server โ real backend API structure.
If you understand this topic properly, you can build production-level APIs.
๐ง What is a REST API?
REST = Representational State Transfer
Simple meaning:
๐ Backend exposes URLs
๐ Frontend sends HTTP requests
๐ Backend returns data (usually JSON)
๐ฅ REST API Structure
REST follows resources-based URLs.
Example resource: users
Instead of:
-
/addUser-
/deleteUserREST style:
- POST
/users- PUT
/users/:id- DELETE
/users/:id๐ HTTP Methods in REST
- GET -> Read data
- POST -> Create data
- PUT -> Update data
- DELETE -> Remove data
These map directly to CRUD.
๐งฉ Basic REST API Example
Step 1: Setup Express
const express = require("express");
const app = express();
app.use(express.json()); // middleware for JSON
let users = [
{ id: 1, name: "Amit" },
{ id: 2, name: "Rahul" }
];
๐ 1๏ธโฃ GET โ Fetch all users
app.get("/users", (req, res) => {
res.json(users);
});
โ 2๏ธโฃ POST โ Add new user
app.post("/users", (req, res) => {
const newUser = {
id: users.length + 1,
name: req.body.name
};
users.push(newUser);
res.json(newUser);
});
โ๏ธ 3๏ธโฃ PUT โ Update user
app.put("/users/:id", (req, res) => {
const id = parseInt(req.params.id);
const user = users.find(u => u.id === id);
if (!user) {
return res.status(404).json({ message: "User not found" });
}
user.name = req.body.name;
res.json(user);
});
โ 4๏ธโฃ DELETE โ Remove user
app.delete("/users/:id", (req, res) => {
const id = parseInt(req.params.id);
users = users.filter(u => u.id !== id);
res.json({ message: "User deleted" });
});
โถ๏ธ Start Server
app.listen(3000, () => {
console.log("Server running on port 3000");
});
๐ง What is Routing?
Routing means:
๐ Matching URL
๐ Matching HTTP method
๐ Running correct function
Example:
- GET /users โ fetch users
- POST /users โ create user
๐ Better Folder Structure (Real Projects)
project/
โโโ routes/
โ โโโ userRoutes.js
โโโ controllers/
โโโ server.js
Separation of concerns = scalable backend.
โ ๏ธ Common Beginner Mistakes
- Not using express.json()
- Not parsing req.params correctly
- Not sending status codes
- Not handling missing data
๐งช Mini Practice Task
- Create REST API for products
- GET
/products- POST
/products- PUT
/products/:id- DELETE
/products/:idโก๏ธ Double Tap โฅ๏ธ For More