Student Activity
Student Activity (30-min)
Step-by-Step Procedure
Create a REST API for Managing a List of Tasks (15 min):
Step 1: Set up a new project:
bash코드 복사mkdir task-api cd task-api npm init -y npm install expressStep 2: Create a file named
server.jsand add the following code:javascript코드 복사const express = require('express'); const app = express(); app.use(express.json()); const tasks = [ { id: 1, title: 'Task 1', completed: false }, { id: 2, title: 'Task 2', completed: true } ]; // GET all tasks app.get('/tasks', (req, res) => { res.json(tasks); }); // POST a new task app.post('/tasks', (req, res) => { const task = { id: tasks.length + 1, ...req.body }; tasks.push(task); res.status(201).json(task); }); // PUT to update a task app.put('/tasks/:id', (req, res) => { const task = tasks.find((t) => t.id === parseInt(req.params.id)); if (!task) return res.status(404).send('Task not found'); Object.assign(task, req.body); res.json(task); }); // DELETE a task app.delete('/tasks/:id', (req, res) => { const taskIndex = tasks.findIndex((t) => t.id === parseInt(req.params.id)); if (taskIndex === -1) return res.status(404).send('Task not found'); tasks.splice(taskIndex, 1); res.status(204).send(); }); const PORT = 3000; app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));Step 3: Run the server:
bash코드 복사node server.jsStep 4: Verify the server is running:
Open a browser and navigate to
http://localhost:3000/tasks.
Test the API Using Postman (15 min):
Step 1: Open Postman and create a new collection named
Task API.Step 2: Test the following endpoints:
GET
/tasks:Check if the list of tasks is returned.
POST
/tasks:Add a new task by sending JSON data in the body:
json코드 복사{ "title": "New Task", "completed": false }
PUT
/tasks/:id:Update an existing task by specifying its
idand new data:json코드 복사{ "title": "Updated Task", "completed": true }
DELETE
/tasks/:id:Delete a task by its
id.
Last updated