// Import Express
const express = require('express');
const app = express();
// Middleware to parse JSON request bodies
app.use(express.json());
// In-memory JSON object simulating a database (e.g., a list of students)
let students = [
{ id: 1, name: 'Alice', age: 22 },
{ id: 2, name: 'Bob', age: 24 }
];
// GET endpoint: Retrieve all students
app.get('/students', (req, res) => {
res.json(students);
});
// POST endpoint: Add a new student
app.post('/students', (req, res) => {
const newStudent = req.body;
// Simple ID assignment (for demo purposes)
newStudent.id = students.length ? students[students.length - 1].id + 1 : 1;
students.push(newStudent);
res.status(201).json(newStudent);
});
// PUT endpoint: Update a student's details
app.put('/students/:id', (req, res) => {
const studentId = parseInt(req.params.id);
const index = students.findIndex(student => student.id === studentId);
if (index !== -1) {
students[index] = { ...students[index], ...req.body };
res.json(students[index]);
} else {
res.status(404).send('Student not found');
}
});
// DELETE endpoint: Remove a student
app.delete('/students/:id', (req, res) => {
const studentId = parseInt(req.params.id);
const initialLength = students.length;
students = students.filter(student => student.id !== studentId);
if (students.length < initialLength) {
res.status(204).send(); // No Content
} else {
res.status(404).send('Student not found');
}
});
// Start the server
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});