Express: Course Management
Develop an Express.js application that provides basic functionality for managing student records. Each student should have an id, name, and course. Initialize the application with at least three student records in an in-memory array. The application must implement the following:
GET /students
: This route should return a list of all students.GET /students/:id
: This route should return details of a single student based on the ID provided in the URL.POST /students
: This route should accept a new student's name and course via the request body, assign a unique ID, add the student to the array, and return a message confirming the addition.PUT /students/:id
: This route should update the student’s name and/or course for the given ID. If the student does not exist, the server should return a 404 error.DELETE /students/:id
: This route should remove a student from the list and return the details of the deleted student.Use
express.json()
middleware to parse JSON input, and useres.send()
for all output. Ensure appropriate status codes and messages are used for both success and error responses.
app.js
import express from 'express';
const app = express();
const PORT = 3000;
// Middleware to parse JSON bodies
app.use(express.json());
// In-memory data store for students
let students = [
{ id: 1, name: 'John Doe', course: 'Computer Science' },
{ id: 2, name: 'Jane Smith', course: 'Mathematics' },
{ id: 3, name: 'Peter Jones', course: 'Physics' }
];
// Variable to manage the next unique ID
let nextId = 4;
// --- Routes ---
// GET /students - Retrieve all students
app.get('/students', (req, res) => {
const responseText = students.map(s => `ID: ${s.id}, Name: ${s.name}, Course: ${s.course}`).join('\n');
res.status(200).send(responseText);
});
// GET /students/:id - Retrieve a single student
app.get('/students/:id', (req, res) => {
const studentId = parseInt(req.params.id, 10);
const student = students.find(s => s.id === studentId);
if (!student) {
return res.status(404).send('Error: Student not found.');
}
const responseText = `ID: ${student.id}\nName: ${student.name}\nCourse: ${student.course}`;
res.status(200).send(responseText);
});
// POST /students - Add a new student
app.post('/students', (req, res) => {
const { name, course } = req.body;
const newStudent = { id: nextId++, name, course };
students.push(newStudent);
res.status(201).send(`Student added successfully with ID: ${newStudent.id}`);
});
// PUT /students/:id - Update an existing student
app.put('/students/:id', (req, res) => {
const studentId = parseInt(req.params.id, 10);
const { name, course } = req.body;
const student = students.find(s => s.id === studentId);
if (!student) {
return res.status(404).send('Error: Student not found.');
}
if (name !== undefined) student.name = name;
if (course !== undefined) student.course = course;
res.status(200).send(`Student with ID: ${studentId} updated successfully.`);
});
// DELETE /students/:id - Remove a student
app.delete('/students/:id', (req, res) => {
const studentId = parseInt(req.params.id, 10);
const studentIndex = students.findIndex(s => s.id === studentId);
if (studentIndex === -1) {
return res.status(404).send('Error: Student not found.');
}
const [deletedStudent] = students.splice(studentIndex, 1);
const responseText = `Deleted Student Details:\nID: ${deletedStudent.id}\nName: ${deletedStudent.name}\nCourse: ${deletedStudent.course}`;
res.status(200).send(responseText);
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Test the API with Postman
Get all students (GET
)
Set the method to GET and the URL to
http://localhost:3000/students
.Click Send. You will see the list of all students as plain text.
Get a single student (GET
)
Set the method to GET and the URL to
http://localhost:3000/students/2
.Click Send. You will see the details for Jane Smith.
Add a new student (POST
)
Set the method to POST and the URL to
http://localhost:3000/students
.Go to the Body tab, select raw, and choose JSON.
Enter the new student's data:
{
"name": "Emily White",
"course": "Chemistry"
}
Click Send. You will get a plain text confirmation message.
Update a student's course (PUT
)
Set the method to PUT and the URL to
http://localhost:3000/students/1
.Go to the Body tab, select raw, and choose JSON.
Enter the field to update:
{
"course": "Advanced Computer Science"
}
Click Send. You will receive a plain text success message.
Delete a student (DELETE
)
Set the method to DELETE and the URL to
http://localhost:3000/students/3
.Click Send. The response body will show the details of the student who was deleted.