Chapter 6Node.js & Express~1 min read
REST API बनवणे
Full CRUD API
REST API म्हणजे HTTP methods वापरून data manage करणारी API. आपण in-memory data (array) वापरून एक complete CRUD (Create, Read, Update, Delete) API बनवू.
Complete CRUD API example
javascript
const express = require('express');
const app = express();
app.use(express.json());
// In-memory database
let students = [
{ id: 1, name: "Avadhoot", grade: "A" },
{ id: 2, name: "Rahul", grade: "B" },
];
let nextId = 3;
// GET /students — सगळे students मिळवा
app.get('/students', (req, res) => {
res.json(students);
});
// GET /students/:id — specific student
app.get('/students/:id', (req, res) => {
const student = students.find(s => s.id === Number(req.params.id));
if (!student) return res.status(404).json({ error: 'Student not found' });
res.json(student);
});
// POST /students — नवीन student add करा
app.post('/students', (req, res) => {
const { name, grade } = req.body;
if (!name || !grade) return res.status(400).json({ error: 'name और grade required' });
const newStudent = { id: nextId++, name, grade };
students.push(newStudent);
res.status(201).json(newStudent);
});
// PUT /students/:id — student update करा
app.put('/students/:id', (req, res) => {
const idx = students.findIndex(s => s.id === Number(req.params.id));
if (idx === -1) return res.status(404).json({ error: 'Not found' });
students[idx] = { ...students[idx], ...req.body };
res.json(students[idx]);
});
// DELETE /students/:id — student delete करा
app.delete('/students/:id', (req, res) => {
const idx = students.findIndex(s => s.id === Number(req.params.id));
if (idx === -1) return res.status(404).json({ error: 'Not found' });
const deleted = students.splice(idx, 1);
res.json({ deleted: deleted[0] });
});
app.listen(3000, () => console.log('Server running on port 3000'));💡
API test करण्यासाठी Postman किंवा Thunder Client (VS Code extension) वापरा. Browser फक्त GET requests करतो, POST/PUT/DELETE साठी tools लागतात.
✅ Key Points — लक्षात ठेवा
- ▸GET = Read, POST = Create, PUT = Update, DELETE = Delete
- ▸200 OK, 201 Created, 400 Bad Request, 404 Not Found
- ▸res.status(code).json(data) — status + response
- ▸req.body — POST/PUT body (express.json() लागतो)
- ▸Validate input — 400 error पाठवा if invalid
0/8 chapters पूर्ण