Routing Basics — GET/POST for Biryani API
Routing is how your server decides which function to call based on the URL and HTTP method — like Swiggy routing orders to the right restaurant.
In Express, routing means matching incoming requests to specific handler functions based on two things:
- HTTP Method — GET (read data), POST (create data), PUT (update), DELETE (remove)
- URL Path — /biryani, /orders, /users
Think of it like Swiggy's order system:
- When you open the app to see restaurants — that's a GET request to
/restaurants - When you place an order — that's a POST request to
/orders - When you check delivery status — that's a GET request to
/orders/:id
Express makes routing incredibly simple with intuitive methods:
import express from 'express';
const app = express();
// GET route — read data (like viewing menu)
app.get('/biryani', (req, res) => {
res.json({ message: 'Biryani menu loaded!' });
});
// POST route — create data (like placing order)
app.post('/biryani', (req, res) => {
res.status(201).json({ message: 'Biryani added!' });
});
app.listen(3000);
Each route has three parts: method (app.get), path ('/biryani'), and handler ((req, res) => { ... }). The handler receives the request and sends the response.
GET is the most common HTTP method. It's used to retrieve data — like reading a menu, listing restaurants, or fetching user details. GET requests should never change data on the server.
Creating a GET /biryani route:
import express from 'express';
const app = express();
// In-memory biryani menu
let biryaniMenu = [
{ id: 1, name: 'Chicken Biryani', price: 250, spice: 'Medium' },
{ id: 2, name: 'Mutton Biryani', price: 350, spice: 'High' },
{ id: 3, name: 'Veg Biryani', price: 200, spice: 'Low' }
];
// GET /biryani — Full menu dekhlo
app.get('/biryani', (req, res) => {
res.json({
success: true,
count: biryaniMenu.length,
data: biryaniMenu
});
});
app.listen(3000, () => {
console.log('Biryani API running on port 3000');
});
Testing with curl:
curl http://localhost:3000/biryani
You'll get back a JSON array of biryani items. The res.json() method automatically sets the Content-Type header to application/json and converts your object to a JSON string.
Important: GET requests should be idempotent — calling them multiple times should not change anything. It's like looking at a menu: reading it 10 times doesn't change the prices.
POST is used to create new data on the server. When you add a new biryani to the menu, you send a POST request with the biryani details in the request body.
Creating a POST /biryani route:
import express from 'express';
const app = express();
// IMPORTANT: Parse JSON bodies
app.use(express.json());
let biryaniMenu = [
{ id: 1, name: 'Chicken Biryani', price: 250, spice: 'Medium' }
];
let nextId = 2;
// POST /biryani — Naya biryani add karo
app.post('/biryani', (req, res) => {
const { name, price, spice } = req.body;
// Validation — bina naam ke biryani nahi chalegi!
if (!name || !price) {
return res.status(400).json({
success: false,
message: 'Name and price are required! Biryani bina naam ke kaise bhejein?'
});
}
const newBiryani = {
id: nextId++,
name,
price,
spice: spice || 'Medium'
};
biryaniMenu.push(newBiryani);
// 201 = Created (not 200!)
res.status(201).json({
success: true,
message: 'Biryani successfully added to menu!',
data: newBiryani
});
});
app.listen(3000);
Testing with curl:
curl -X POST http://localhost:3000/biryani \
-H "Content-Type: application/json" \
-d '{"name": "Prawn Biryani", "price": 400, "spice": "High"}'
Key difference from GET:
- POST uses
req.bodyto receive data (requiresexpress.json()middleware) - POST returns status 201 Created instead of 200 OK
- POST modifies data on the server (creates new records)
req.body is where all incoming JSON data lives. When a client sends JSON in a POST request, Express parses it and makes it available at req.body — but only if you've added the express.json() middleware!
Without express.json():
// req.body will be UNDEFINED!
app.post('/biryani', (req, res) => {
console.log(req.body); // undefined 😭
});
With express.json():
app.use(express.json());
app.post('/biryani', (req, res) => {
console.log(req.body.name); // 'Prawn Biryani'
console.log(req.body.price); // 400
console.log(req.body.spice); // 'High'
});
What the client sends vs what Express gives you:
| Client sends (raw JSON) | Express gives (req.body) |
|---|---|
{"name":"Chicken Biryani","price":250} | { name: 'Chicken Biryani', price: 250 } |
Express parses the JSON string into a JavaScript object automatically. This is like Swiggy receiving an order form and converting it into a structured order in their system. Without express.json(), the raw request body is just a stream of bytes — unusable!
Always put express.json() at the top, before any route that reads req.body. Middleware order matters!
HTTP status codes are the server's way of telling the client what happened. Think of them like Swiggy order status messages:
| Code | Meaning | Swiggy Analogy |
|---|---|---|
| 200 OK | Request succeeded (default for GET) | Menu loaded successfully! |
| 201 Created | Resource created (default for POST) | Order placed successfully! |
| 400 Bad Request | Client sent invalid data | Wrong address entered |
| 404 Not Found | Resource doesn't exist | Restaurant closed / not found |
| 500 Internal Server Error | Server crashed | Swiggy server phat gaya 😅 |
Setting status codes in Express:
// Default 200 — res.json() automatically uses 200
res.json({ data: biryaniMenu });
// 201 Created — for successful POST
res.status(201).json({ message: 'Created!' });
// 400 Bad Request — client error
res.status(400).json({ error: 'Invalid data' });
// 404 Not Found — resource missing
res.status(404).json({ error: 'Not found' });
// 500 Server Error — something broke
res.status(500).json({ error: 'Server error' });
Method chaining: res.status(201).json(data) is method chaining — res.status() sets the status code and returns the response object, then .json() sends the response. This is much cleaner than raw Node's res.writeHead(201, { ... }) followed by res.end().
Quick rule: GET = 200, POST = 201, validation error = 400, not found = 404, server crash = 500.
Key Takeaways
- ✅ Routing = HTTP method + URL path. app.get() for reading, app.post() for creating.
- ✅ GET returns 200 OK and should never modify server data (idempotent).
- ✅ POST returns 201 Created and uses req.body for incoming data.
- ✅ app.use(express.json()) is REQUIRED before any route that reads req.body.
- ✅ Always validate input — return 400 if data is missing or invalid.
- ✅ res.status(code).json(data) = set status code + send JSON in one chain.
- ✅ Status codes: 200 OK, 201 Created, 400 Bad Request, 404 Not Found, 500 Server Error.
Want to track your progress?
Log in to save your place and pick up where you left off.
Progress track karna chahte ho?
Login karo apni progress save karne ke liye aur jahan chhoda tha wahan se shuru karo.
Login