Create your first REST API with Node.js, Koa.js and MongoDB

Mohammed Rishard
9 min readApr 17, 2021

Before we begin to create the API let’s make sure we understand few terms.

What is an API?

API stands for Application Programming Interface. It is a set of programming code that allows data transmission between multiple applications. Simply API is the messenger that takes the requests and tells the system what you want to do and then returns the response to you.

If you need to know further details about API, please read my article on API

What is REST?

REST stands for Representational State Transfer. It is a software architectural style followed when designing APIs. It proposes a set of rules web developers should follow when building APIs. REST is lightweight, scalable and maintainable. In order for an API to be REST, it should follow 6 constraints.

If you need to know further details about REST you can read my previous blog on REST.

So, REST API means APIs that follow REST architecture in order to perform some operations. So simply REST API means a set of URLs used to perform CRUD operations on resources. Each URL is called a request while the data sent back to you is called a response.

In this article, we are going to build a REST API using Node.js, Koa.js and MongoDB. In order to make the explanation easier, I will be creating a REST API to manage products in an e-commerce store. So, let’s begin.

Node.JS

First, we need to verify that Node is installed on our computer. You can check whether it is installed by using the following command.

In the terminal type –

node -v

If this command displays the version then Node.js has already been installed. Else, if it displays something like “Command not found”, then you have to install node to your computer. You can download Node.js at https://nodejs.org/en/

Npm

NPM stands for Node Package Manager. In order to manage the Node Packages, we need to have npm installed on our machine. We can verify whether we have installed npm in our machine by typing the below command in the terminal.

npm -v

If this command displays the version then npm has already been installed. Else, if it displays something like “Command not found”, then you have to install npm. You can install the latest version of npm by typing the below command in the terminal.

npm install npm@latest -g

Mongo DB

We will be using MongoDB as our database to store the data. MongoDB is a NoSQL document database which means it stores data in JSON like documents. It has a powerful query language. You can verify whether you have installed Mongo DB in your machine by typing the below command in the terminal.

mongo — version

If it returns the version, then you have already installed Mongo DB. If not, you need to install Mongo DB. If you want to learn more about MongoDB, how to install MongoDB and how to implement the basic CRUD Operations in MongoDB, please refer to my article on MongoDB.

Create a new Project

Now let’s start working on our project. So I will create a folder named REST and I will initialize my node project. To do that initially open the terminal and go to the location where you want to create the project and then do the following.

mkdir REST

cd REST

Initializing a node.js project

You can initialize a Node.js project by typing npm init inside the REST directory.

You’ll be asked a series of questions when you first start using node.js. To create package.json, all you have to do is choose a default name, add a description, choose the author’s name, and choose a default License. Don’t panic if you make a mistake; you can still correct it later.

Now we have installed Node.js, now let’s install Koa.js.

Installing Koa.js

We will be using Koa.js instead of express.js for our project. Because Koa.js is very lightweight and very easy to use compared to Express.js. If you need to learn more about Koa.js take a look at my article on Introduction to Koa.js.

The npm install koa — save command can be used to install koa. This will install all the dependencies.

Setting up the project

Now it’s time to open the project using your favourite IDE. I will be using Webstorm but you can use any IDE. After you have opened the project in your IDE, create a new file named index.js. This will be the starter file for our project. Let’s add the following code to index.js and try running our server.

Now you have typed all the necessary codes, So, run the server using the following code in the project directory.

node index

Open your browser and go to https://localhost:3000 and you will get the following screen.

Congratulations you have successfully created your first Koa.js application. If you didn’t get this screen, please make sure you followed the steps correctly.

Setup MongoDB

Since we will be using MongoDB as our database, We need to install the MongoDB driver to our application.

npm install mongodb –save

Once you have installed the MongoDB driver we will set up the mongo client. To do that initially we will create a new directory called ‘dal’ within our project folder in order to keep all the DB related code. Inside the ‘dal’ folder create a JavaScript file named index.js and add the below code.

This code will connect our application to Mongo DB. Now restart your server and check whether you get the “Successfully Connected to MongoDB” message, if so, you have successfully connected to MongoDB. If not make sure you have followed everything correctly.

Implementing the CRUD Operations

As I mentioned earlier, I will be creating a REST API to manage products in a store. So initially before creating the routes we need to implement the CRUD operations. For now, I will implement the CRUD of Products with some fields. We will be adding the product to the database, retrieve all the products, retrieve a specific product based on the id, update it and delete it. I will include the following fields for the Product model.

· Name

· Description

· Qty

· Price

Now, let’s code our CRUD operations. Inside the ‘dal’ folder create a JavaScript file named products.dao.js and add the below code.

Database calls are asynchronous. Therefore, in order to handle them async and await has been used. In the end, all these methods have been exported so that we can use them in our API methods.

Creating API methods

We have successfully completed the implementation of the CRUD operations. Now let’s map the CRUD operations to methods so that we use them in our routes. All the API route calls will be sent to the crud methods in products.dao.js via these API methods. Create a new folder named API and inside this folder create a JavaScript file named products.api.js and add the below code.

Finally, export the methods so that we can use them in routes

Creating Routes

It is better that if we plan the endpoints (routes) before starting to code the routes.

The routes we will need to create our API are:

· GET /product — Retrieves all products

· GET /product/{id} — Retrieves a single product

· POST /product — Inserts a new product

· PUT /product/{id} — Updates a single product

· DELETE /product/{id} — Deletes a single product

Now we have successfully decided the endpoints that we will be needing to perform CRUD operations on Products. So, let’s start coding the routes.

Implementing the Routes

Create a new folder named ‘routes’ and within that folder create a new JavaScript file named ‘products.routes.js’, We will be coding our routes in this file. Before start coding, we will need to install the ‘’@koa/router” package to handle the routing.

You can install this by using the below command.

npm install @koa/router — save

After this has been installed, add the below code in the products.routes.js file in order to create the API routes.

So now we have successfully created the routes. Next, we can register our routes with Koa. Before that let’s install “Bodyparser”. Body-Parser enables our app to parse the data coming from the request so that we can use the data.

Installing Body Parser

You can install BodyParser by using the below code.

npm install body-parser –save

Registering the routes

We need to register the routes so that we use them in our application. This is a very simple process in Koa.js. So to do that go to the index.js that we created initially and replace it with the below code.

Congratulations! You have successfully created your first REST API. Now let’s try testing our API.

Demo

We will be using Postman to test our API. If you have not installed Postman please download it from here and then install it.

Now let’s begin testing our API. So initially start your server using node index command and then open Postman.

POST Request

Let us add a product using the POST request. For that as the URL use localhost:3000/products and select the request type as POST and navigate to the body and choose the x-www-form-urlencoded option as I have selected below. Then add the following fields and values and click Send.

If your request was successful the inserted data will be displayed in the body as shown above or else if there was an error such as “Not found” make sure you have started your node server.

You can try adding multiple data with different values and check your API.

GET Request

Now, let’s make a GET request and check whether we can retrieve all the products in our DB.

So now we are able to get all the products from the database.

GET BY ID Request

So now let’s try to get a product from its id. To do that copy the id of a product and paste it in the URL and make a GET request and check whether you are able to get that product.

PUT REQUEST

So let’s try to edit the product we inserted earlier. Copy the id of that product and paste it in the URL and then select the request type as PUT and navigate to the body and choose the x-www-form-urlencoded option and then enter the edited data in key-value pairs.

After you click send you will be able to see the updated product data in the body.

Similarly, you can also try the Delete request using postman. It is similar to the way we used GET request to get by id. But here you need to select DELETE as the request type.

Woah! Everything worked perfectly. We created a simple REST API to handle the CRUD operations of products using Node.js, Koa.js and MongoDB. Did you enjoy making your first REST API? Please let me know if you have any questions or if you get stuck anywhere, in the comments below. I am ready to help. You can also view and run the project directly from my Github repository. Hope you learned something.

Thank you!

--

--