Mini Project 2: RESTful Task Manager API with Express
Introduction
This project involves creating a RESTful Task Manager API using Express.js. The API allows users to perform CRUD (Create, Read, Update, Delete) operations on a collection of tasks. It also incorporates middleware for logging, validation, and error handling, providing students with practical experience in API development.
Motivation
With the growing importance of REST APIs in modern web applications, this project highlights the importance of understanding API design principles. By building a functional API, students can grasp how to manage routes, handle HTTP requests, and validate input data effectively.
Functionality of Project
The API supports the following features: 1. **Add a New Task (POST):** Adds a new task to the collection. 2. **Retrieve All Tasks (GET):** Returns a list of tasks in JSON format. 3. **Update an Existing Task (PUT):** Updates the details of a task identified by its ID. 4. **Delete a Task (DELETE):** Removes a task from the collection. 5. **Middleware:** Includes request logging and validation of task payloads.
Technical Explanation and Code Implementation
The project utilizes Express.js, a popular web framework for Node.js. Middleware is used to validate input data and handle errors. Below are the key components and code examples.
1. Middleware for Logging
A custom middleware logs the HTTP method and URL for every incoming request.
// Some code
app.use((req, res, next) => {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
next();
});
2. Adding a New Task
A POST endpoint adds a new task to the collection. Input validation ensures that the payload contains valid data for 'title' and 'completed'.
// Some code
app.post('/tasks', [
check('title').isString().notEmpty(),
check('completed').isBoolean()
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const task = { id: tasks.length + 1, ...req.body };
tasks.push(task);
res.status(201).json(task);
});
Result and Conclusion
This project highlights the key aspects of REST API development using Express.js. Students learn to handle routes, implement middleware, and validate data, which are foundational skills for back-end development in modern web applications.
Last updated