Student Activity
Student Activity (30-min)
Activity: Create a RESTful Task Management API
Step-by-Step Procedure:
Step 1: Set Up the Application:
Initialize the project and install dependencies:
bash코드 복사mkdir task-api cd task-api npm init -y npm install express
Step 2: Define the API Structure:
Create
app.jsand add the following code:javascript코드 복사const express = require('express'); const app = express(); app.use(express.json()); let 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 newTask = { id: tasks.length + 1, ...req.body }; tasks.push(newTask); res.status(201).json(newTask); }); // 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: Test the API Using Postman:
Test the following endpoints:
GET
/tasks: Returns the list of tasks.POST
/tasks: Creates a new task. Example body:json코드 복사{ "title": "New Task", "completed": false }PUT
/tasks/:id: Updates a task by ID. Example body:json코드 복사{ "title": "Updated Task", "completed": true }DELETE
/tasks/:id: Deletes a task by ID.
Step 4: Validate Responses:
Check if JSON responses are properly formatted and include the expected data.
Last updated