Introduction

Task management is a crucial part of any project, and creating a Task Manager API can streamline the process of managing tasks in a systematic and efficient manner. In this tutorial, we will walk you through the process of building a Task Manager API using Node.js, Express, MongoDB, and deploying it to Heroku. We’ll cover everything from setting up the project to implementing the API endpoints with coding examples.

Prerequisites

Before we start building our Task Manager API, make sure you have the following prerequisites in place:

  1. Node.js: Ensure that Node.js is installed on your system. You can download it from nodejs.org.
  2. npm (Node Package Manager): npm comes bundled with Node.js. You can check its version by running npm -v in your terminal.
  3. MongoDB: You’ll need a MongoDB database to store task data. You can either install MongoDB locally or use a cloud-based service like MongoDB Atlas.
  4. Heroku Account: Sign up for a Heroku account if you haven’t already. You’ll use Heroku to deploy your API.
  5. Text Editor/IDE: Choose a text editor or integrated development environment (IDE) that you are comfortable with. Popular choices include Visual Studio Code, Sublime Text, or WebStorm.

Setting Up the Project

Let’s start by setting up the project structure and installing the necessary dependencies.

  1. Create a new project folder and navigate to it in your terminal:
bash
mkdir task-manager-api
cd task-manager-api
  1. Initialize a Node.js project:
bash
npm init -y
  1. Install the required packages: Express, Mongoose, and other dependencies:
bash
npm install express mongoose body-parser cors dotenv
  • Express: A fast, unopinionated, minimalist web framework for Node.js.
  • Mongoose: An elegant MongoDB object modeling tool.
  • body-parser: Middleware for parsing incoming request bodies.
  • cors: Middleware for handling Cross-Origin Resource Sharing.
  • dotenv: Used for managing environment variables.
  1. Create the main server file, app.js, in the project root directory.

Setting Up MongoDB

Before we proceed, ensure that you have a MongoDB database ready. You can set up a local MongoDB instance or use a cloud-based service like MongoDB Atlas. Update the MongoDB connection URL in your app.js file as follows:

javascript
const mongoose = require('mongoose');
const dotenv = require('dotenv');
dotenv.config();const DB_URL = process.env.MONGODB_URI || ‘mongodb://localhost/task-manager’;

mongoose.connect(DB_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false,
});

const db = mongoose.connection;

db.on(‘error’, console.error.bind(console, ‘MongoDB connection error:’));
db.once(‘open’, () => {
console.log(‘Connected to MongoDB’);
});

Creating the Task Model

Now, let’s define the Task model using Mongoose. In a new folder called models, create a file named task.js to define the schema for our tasks:

javascript

const mongoose = require('mongoose');

const taskSchema = new mongoose.Schema({
description: {
type: String,
required: true,
trim: true,
},
completed: {
type: Boolean,
default: false,
},
});

const Task = mongoose.model(‘Task’, taskSchema);

module.exports = Task;

This schema includes a description field for the task description and a completed field to track whether the task is completed or not.

Creating API Endpoints with Express

Now that we have set up the database and the model, let’s create the API endpoints using Express.

In your app.js file, add the following code to set up Express and define the API routes:

javascript
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const Task = require('./models/task');
const app = express();
const port = process.env.PORT || 3000;app.use(bodyParser.json());
app.use(cors());

// Create a new task
app.post(‘/tasks’, async (req, res) => {
try {
const task = new Task(req.body);
await task.save();
res.status(201).send(task);
} catch (error) {
res.status(400).send(error);
}
});

// Get all tasks
app.get(‘/tasks’, async (req, res) => {
try {
const tasks = await Task.find();
res.send(tasks);
} catch (error) {
res.status(500).send(error);
}
});

// Get a task by ID
app.get(‘/tasks/:id’, async (req, res) => {
const _id = req.params.id;
try {
const task = await Task.findById(_id);
if (!task) {
return res.status(404).send(‘Task not found’);
}
res.send(task);
} catch (error) {
res.status(500).send(error);
}
});

// Update a task by ID
app.patch(‘/tasks/:id’, async (req, res) => {
const updates = Object.keys(req.body);
const allowedUpdates = [‘description’, ‘completed’];
const isValidOperation = updates.every((update) =>
allowedUpdates.includes(update)
);

if (!isValidOperation) {
return res.status(400).send(‘Invalid updates’);
}

const _id = req.params.id;

try {
const task = await Task.findByIdAndUpdate(_id, req.body, {
new: true,
runValidators: true,
});

if (!task) {
return res.status(404).send(‘Task not found’);
}

res.send(task);
} catch (error) {
res.status(400).send(error);
}
});

// Delete a task by ID
app.delete(‘/tasks/:id’, async (req, res) => {
const _id = req.params.id;
try {
const task = await Task.findByIdAndDelete(_id);
if (!task) {
return res.status(404).send(‘Task not found’);
}
res.send(task);
} catch (error) {
res.status(500).send(error);
}
});

app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});

This code defines the following API endpoints:

  • POST /tasks: Create a new task.
  • GET /tasks: Get all tasks.
  • GET /tasks/:id: Get a task by ID.
  • PATCH /tasks/:id: Update a task by ID.
  • DELETE /tasks/:id: Delete a task by ID.

Testing Your API Locally

To test your API locally, run the following command in your terminal:

bash
node app.js

Your API will be accessible at http://localhost:3000 by default. You can use tools like Postman or cURL to interact with your API.

Deploying to Heroku

Now that your Task Manager API is up and running locally, it’s time to deploy it to Heroku.

  1. Install the Heroku CLI if you haven’t already. You can find installation instructions on the Heroku website.
  2. Log in to your Heroku account using the following command:
bash
heroku login
  1. Create a new Heroku app:
bash
heroku create your-task-manager-app-name
  1. Deploy your app to Heroku:
bash
git push heroku master
  1. Once the deployment is complete, open your app in the browser:
bash
heroku open

Your Task Manager API is now live on Heroku!

Conclusion

In this tutorial, we have walked through the process of building a Task Manager API using Node.js, Express, MongoDB, and deploying it to Heroku. You have learned how to set up the project, create a MongoDB database, define a Mongoose model, and implement API endpoints for tasks. This API can serve as a foundation for building task management applications, and you can further enhance it by adding features like user authentication and more advanced task management functionality.

Remember to secure your API by implementing proper authentication and authorization mechanisms before deploying it to a production environment. Happy coding!