Build a REST API Using Node.js, Express.js, and MongoDB, and Test It on Postman

In this tutorial, we are going to build a REST API using Node.js with MongoDB database. But what is an API?

Ankan Das
JavaScript in Plain English

--

What is an API?

API is the acronym for Application Programming Interface, which is a software intermediary that allows two applications to talk to each other. Each time you use an app like Facebook, send an instant message or check the weather on your phone, you’re using an API.

Prerequisite for Tutorial:

  1. Nodejs installed in Your System
  2. Basic knowledge of JavaScript
  3. Understanding any database (Relational/Non-Relational)

Don’t worry! If you don’t know all of these in the first row, you will learn all of them in this tutorial.

1. Project Setup:

Here I am using VS code as my code editor and MongoDB atlas to store all the data. The entire project structure should look like this:

Create a folder in your system and name it as “API”. You can name it as you want. Open this folder inside your code editor and go to the terminal.

Inside your terminal type

“npm init”

The “npm init” command will initialize a project and create the package.json file.

After that, we need to install Express.js and all the other dependencies for the project.

Again type the following in the terminal:

npm install express dotenv mongoose body-parser cors

So express will handle our server, dotenv allows you to separate secrets from your source code. Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB. The body-parser module parses the JSON, buffer, string, and URL encoded data submitted using HTTP POST request. CORS stands for Cross-Origin Resource Sharing. It allows us to relax the security applied to an API.

And now we will install nodemon, so type in the terminal:

npm install -g nodemon

The nodemon Module is a module that develops node.js-based applications by automatically restarting the node application when file changes in the directory are detected.

After installation, add the following in the script section of your package.json file:

After you have installed everything, go to the package.json file and verify your dependencies section. It should look like this, versions may differ.

2. Server Setup:

Let’s create our very first server. Create a file name server.js and write this code:

Create a file name “.env” and put this code inside it.

Here we have added a port number and the MongoDB connection URL. Let me tell you how you can get the MongoDB URL in the first place.

3. Database Setup:

Go to MongoDB Atlas and create a cluster, it may take a few minutes to set up. And after that, click on connect and then Connect Your application. You will then get your MongoDB connection URL.

4. Model Setup:

For every data in the database, we need a model through which we can upload and maintain proper data. Here we are using mongoose to create the model for the database.

5. Routes Setup:

Create a folder named “Routes” inside the main directory, create one file named “ todo.js” where all the routes will be established. Now these lines to your todo.js file inside the routes folder.

In this file, we have created 4 routes for getting all the todo items list, creating a todo, updating a specific todo, and deleting one. All the business logic will go to the controller section.

Every incoming request will go to specific controller methods.

6. Controllers Setup:

A controller is the main part of the application where all your business logic will reside. We need specific logic blocks for different methods.

So, in this way we are ready with API end-points. Now the most crucial part is where we are going to test the APIs. Before that open your terminal and run “npm start” to start your application.

7. Postman:

For API testing we are using Postman. You can download the desktop version or use it in the browser.

8. API Testing:

(a). Insert Todo:

Url: http://localhost:3000/api/todos/

Method: POST

Make sure your header is set to this:

Now try to add a todo to it and click SEND.

And we are supposed to see this in your postman:

It means data is inserted successfully. If you still want to check it from the database, you will find this:

(b) List of Todo:

Url: http://localhost:3000/api/todos/

Method: GET

In this way, we can get all the list of todos.

(c) Update Specific Todo:

Url: http://localhost:3000/api/todos/update/XXY667e48c13e3ae5d7XXXX

Method: PUT

You need to pass the specific id at the end of the URL and pass the updated value of the todo in the form data.

(d) Delete specific Todo:

Url: http://localhost:3000/api/todos/delete/61c369c773923cf617beba60

Method: DELETE

In the same way, as the update API works, we need to pass the specific ID at the end of the URL and make the method delete.

So this is it. We have successfully created a REST API using Node.js, Express.js, and MongoDB. Hopefully, this tutorial will help you to understand the basic concept behind every REST API.

Thanks a lot for reading till the end. You can contact me in case you need any help.

Web: https://ankandas.netlify.app
Instagram: https://www.instagram.com/ankaninperson/
GitHub: https://github.com/Ankan982

More content at plainenglish.io. Sign up for our free weekly newsletter. Get exclusive access to writing opportunities and advice in our community Discord.

--

--