Build REST APIs for the To-Do app using NodeJS & MongoDB.

Prathamesh More
5 min readMar 14, 2020

In this article, we’ll look at how to design REST APIs for the To-Do app.

As a backend developer or full-stack engineer, we deal with building REST APIs for web apps or mobile apps. REST APIs are one of the most common kinds of web services available today. They allow various clients including browser apps to communicate with a server via the REST API.

Wikipedia definition

Representational state transfer is a software architectural style that defines a set of constraints to be used for creating Web services. Web services that conform to the REST architectural style, called RESTful Web services, provide interoperability between computer systems on the Internet.

REST APIs should accept JSON for request payload and also send responses to JSON. JSON is the standard for transferring data. Almost every networked technology can use it: JavaScript has built-in methods to encode and decode JSON either through the Fetch API or another HTTP client. Server-side technologies have libraries that can decode JSON without doing much work.

Today we will API for the To-Do app. The app will web app or mobile app. Frontend doesn't matter.

We will perform CRUD operations.

  1. Create task
  2. View task
  3. Update task
  4. Remove task

We will perform these CRUD operations on the database.

Required Softwares: NodeJS, MongoDB, Postman, and Visual Studio Code.

Let’s start

As usual, create a project folder. You can use any favorite code editor. I’m using the Visual Studio Code.

Now Initialise the Node app using npm init . Initialization will walk you through to create apackage.json file. This file is required for running NodeJS app. Take look at apackage.json file, This file stores all metadata like the name of your app, author, entry point, etc. (Disclaimer: Don’t modify the content of this file)

npm init

Now you ready to install the required packages for our project.

  1. Express — Fast, unopinionated, minimalist web framework for Node.js
  2. Mongoose — elegant MongoDB object modeling for Node.js

To install these packages run npm install express mongoose body-parser --save .

Now we are ready to write the actual server code.

Now create aapp.js file in your project directory. This file holds all code.

For the database, I am using MongoDB Atlas. Included with your free cloud database.

Create a free cluster and get a database URL

MongoDB Atlas Connection

First, create a server —

const express = require('express');
const mongoose = require('mongoose');
const app = express();
const PORT = 3000;app.listen(PORT, () => {
console.log('Server listening on ' + PORT);
});

This code will start the server. to run this code type in the terminal

node app.js

Now add database connection —

mongoose.connect(dbURL, { dbName: 'todo' }, (err) => {
if (!err) {
console.log('Connected to database');
} else {
console.log(err);
}
});

Now, create document schema, it’s like defining table structure in SQL.

const ToDoSchema = new mongoose.Schema({
title : String,
description : String,
createdBy : String,
createAt : Date.now
});
mongoose.model('ToDo', ToDoSchema);

The next step is to create routes

Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).

To create To-Do
http://localhost:3000/
To view all To-Do
http://localhost:3000/
To view single To-Do
http://localhost:3000/todo_id
To update To-Do
http://localhost:3000/todo_id
To delete single To-Do
http://localhost:3000/todo_id
To delete all To-Do
http://localhost:3000/
  1. Create To-Do operation —
//Create To-Do
app.post('/', (req, res) => {
const { title, description, createdBy } = req.body;var toDoAdd = new toDo({
title: title,
description: description,
createdBy: createdBy
});
toDoAdd.save((err, todo) => {
if (err) {
res.status(500).json({
err
});
} else {
res.status(200).json({
message: 'To-Do has been created',
todo
});
}
});
});

To send a request to the server, we need a form or we can use the Postman tool

POST method

2. View To-Dos —

//View To-Do
app.get('/', (req, res) => {
toDo.find({}, (err, toDos) => {
if (err) {
res.status(500).json({
err
});
} else {
res.status(200).json({
message: 'All ToDos',
toDos
});
}
});
});

To view all To-Dos send request to the server.

GET method for all To-Dos

3. View single To-Do —

//View Single To-Do
app.get('/:todo_id', (req, res) => {
const { todo_id } = req.params;toDo.findById(todo_id, (err, toDo) => {
if (err) {
res.status(500).json({
err
});
} else {
res.status(200).json({
message: 'To-Do',
toDo
});
}
});
});

To view single To-Do —

To view single To-Do

4. Update To-Do —

//Update Single To-Do
app.patch('/:todo_id', (req, res) => {
const { todo_id } = req.params;const { title, description, createdBy } = req.body;toDo.findByIdAndUpdate(todo_id, {
title: title,
description: description,
createdBy: createdBy
}, (err, toDo) => {
if (err) {
res.status(500).json({
err
});
} else {
res.status(200).json({
message: 'To-Do updated',
toDo
});
}
});
});

To update To-Do —

PATCH method

4. Remove To-Do —

//Remove Single To-Do
app.delete('/:todo_id', (req, res) => {
const { todo_id } = req.params;toDo.findByIdAndDelete(todo_id, (err, toDo) => {
if (err) {
res.status(500).json({
err
});
} else {
res.status(200).json({
message: 'To-Do has been removed',
toDo
});
}
});
});

To delete To-Do —

DELETE method

5. Delete all To-Dos —

//Remove all To-Do
app.delete('/', (req, res) => {
toDo.remove({}, (err, toDo) => {
if (err) {
res.status(500).json({
err
});
} else {
res.status(200).json({
message: 'All To-Do has been removed',
toDo
});
}
});
});

To delete all To-Do —

DELETE method for all delete To-Dos

All code in one file

Happy coding!

--

--

Prathamesh More

Passionate, Self-taught Full Stack Web Developer that loves designing and building modern websites, applications, and APIs.