Express.
js Student API - Cheat Sheet
GET /students
Purpose: Get all students.
Code:
[Link]('/students', (req, res) => {
[Link](students);
});
GET /students/:name
Purpose: Get one student by name.
Code:
[Link]('/students/:name', (req, res) => {
const name = [Link];
const student = [Link](s => [Link]() === [Link]());
if (student) [Link](student);
else [Link](404).send("Student not found");
});
POST /students
Purpose: Add a new student.
Code:
[Link]('/students', (req, res) => {
const { name, scores } = [Link];
if (!name || ) {
return [Link](400).send('Invalid student data');
}
const exists = [Link](s => [Link]() === [Link]());
if (exists) return [Link](409).send('Student already exists');
const newStudent = { name, scores };
[Link](newStudent);
[Link](201).json(newStudent);
});
PUT /students/:name
Purpose: Update a student's scores.
Code:
[Link]('/students/:name', (req, res) => {
const name = [Link];
const { scores } = [Link];
if () {
return [Link](400).send('Scores must be an array');
}
const student = [Link](s => [Link]() === [Link]());
if (!student) return [Link](404).send('Student not found');
[Link] = scores;
[Link]({ message: 'Scores updated', student });
});
DELETE /students/:name
Purpose: Delete a student.
Code:
[Link]('/students/:name', (req, res) => {
const name = [Link];
const index = [Link](s => [Link]() === [Link]());
if (index === -1) return [Link](404).send('Student not found');
const removed = [Link](index, 1);
[Link]({ message: 'Student deleted', student: removed[0] });
});
Concepts Covered
- Express routing & middleware
- RESTful routes: GET, POST, PUT, DELETE
- Query parameters, route parameters, and JSON body parsing
- Array operations: .find(), .findIndex(), .splice()