Express: Task Management
Create an Express.js application to simulate a simple task management system. Each task should have an id, title, description, and a status field (e.g., “pending”, “in-progress”, “completed”). Initialize the application with at least two tasks in an in-memory array. The application must implement the following functionality using appropriate HTTP methods:
GET /tasks
: Return the list of all tasks.GET /tasks/:id
: Return details of a task by its ID.POST /tasks
: Accept a new task's title and description from the request body, assign a unique ID, default the status to “pending”, and add it to the array.PUT /tasks/:id
: Allow the user to update any of the task fields (title, description, or status). Only the provided fields should be updated.DELETE /tasks/:id
: Remove a task by its ID. If the task doesn't exist, return a 404 error.Ensure use of
express.json()
middleware for parsing input andres.send()
for all output messages.
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 tasks
let tasks = [
{ id: 1, title: 'Setup Project', description: 'Initialize the project repository and install dependencies.', status: 'completed' },
{ id: 2, title: 'Develop API', description: 'Create the required API endpoints for the application.', status: 'in-progress' }
];
// Variable to manage the next unique ID
let nextId = 3;
// --- Routes ---
// GET /tasks - Retrieve all tasks
app.get('/tasks', (req, res) => {
const responseText = tasks.map(t => `ID: ${t.id}, Title: ${t.title}, Status: ${t.status}`).join('\n');
res.status(200).send(responseText);
});
// GET /tasks/:id - Retrieve a single task by its ID
app.get('/tasks/:id', (req, res) => {
const taskId = parseInt(req.params.id, 10);
const task = tasks.find(t => t.id === taskId);
if (!task) {
return res.status(404).send('Error: Task not found.');
}
const responseText = `ID: ${task.id}\nTitle: ${task.title}\nDescription: ${task.description}\nStatus: ${task.status}`;
res.status(200).send(responseText);
});
// POST /tasks - Add a new task
app.post('/tasks', (req, res) => {
const { title, description } = req.body;
const newTask = {
id: nextId++,
title,
description,
status: 'pending' // Default status
};
tasks.push(newTask);
res.status(201).send(`Task added successfully with ID: ${newTask.id}`);
});
// PUT /tasks/:id - Update an existing task
app.put('/tasks/:id', (req, res) => {
const taskId = parseInt(req.params.id, 10);
const { title, description, status } = req.body;
const task = tasks.find(t => t.id === taskId);
if (!task) {
return res.status(404).send('Error: Task not found.');
}
// Update only the provided fields
if (title !== undefined) task.title = title;
if (description !== undefined) task.description = description;
if (status !== undefined) task.status = status;
res.status(200).send(`Task with ID: ${taskId} updated successfully.`);
});
// DELETE /tasks/:id - Remove a task by its ID
app.delete('/tasks/:id', (req, res) => {
const taskId = parseInt(req.params.id, 10);
const taskIndex = tasks.findIndex(t => t.id === taskId);
if (taskIndex === -1) {
return res.status(404).send('Error: Task not found.');
}
tasks.splice(taskIndex, 1);
res.status(200).send(`Task with ID: ${taskId} was deleted successfully.`);
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Test the API with Postman
Get all tasks (GET
)
Set the method to GET and the URL to
http://localhost:3000/tasks
.Click Send. You will see the current list of tasks as plain text.
Get a single task (GET
)
Set the method to GET and the URL to
http://localhost:3000/tasks/2
.Click Send. You will see the full details for the "Develop API" task.
Add a new task (POST
)
Set the method to POST and the URL to
http://localhost:3000/tasks
.Go to the Body tab, select raw, and choose JSON.
Enter the new task's data:
{
"title": "Deploy Application",
"description": "Deploy the final application to a cloud server."
}
Click Send. You will get a plain text confirmation. Run the GET /tasks
request again to see that the new task was added with a "pending" status.
Update a task's status (PUT
)
Set the method to PUT and the URL to
http://localhost:3000/tasks/2
.Go to the Body tab, select raw, and choose JSON.
Enter the field to update:
{
"status": "completed"
}
- Click Send. You will receive a success message. Run
GET /tasks/2
again to see the updated status.
Delete a task (DELETE
)
Set the method to DELETE and the URL to
http://localhost:30-00/tasks/1
.Click Send. You will receive a success message confirming the deletion.