Building your own RESTful Application for Testing API’s CRUD Operation…!

API’s and Backend Testing is something that always fascinates me, I just love when API’s return me a meaningful data in JSON format right from the Backend Database. Being a Tester when I started learning about API’s and Webservices and How we can do the Testing of those. I have been exposed to different open and Public API’s that are freely available all over the internet. So, I have started with the same I learned and performed various operations on API’s so that I can learn to Validate these APIs.

Firstly I learned how to test those APIs Manually and then I been learned about many such tools and libraries like cURL, POSTMAN and RestAssured that ease the Testing of API. There are many such tools that help us to Test APIs. But, Even if I am testing those API and validating those, I have always wondered how these API’s get developed, How much effort’s an API developer put in making those API’s. Of course, they use different languages like Java, Python, Node, etc. to build those API and Support. So I also had the zest to learn and develop at least a Basic Backend Application in REST that will talk to Backend Database and support basic operations like GET, POST, DELETE and UPDATE so-called CRUD Operation.

So, Yesterday I have been part of a webinar about how we can build our own API application node js and Mongodb as Backend. I collected recalled every part of it and then implemented the same by learning each tiny detail of it and I am summarizing my learning below, That will help any person to build and Test those API at your own. Here is the Architecture of our App:

Of course, it is very easy for a developer but doing it the first time will always be exciting. So, here I am writing this small blog on How we can develop a RESTful app from scratch that will support Basic API operations. Feel free to comment, correct me and I wish every Tester should at least try to implement this. It will never be perfect as in the real world as compared to Enterprise application and I feel very proud of every developer around the world that make this happen to convert an API contract in code and serves the Business. It is just small joy I want to share about how we can develop our own RESTful Application in Nodejs.

So, Lets Start:

The application we are developing is a simple Employee Record application that will support CRUD APIs, We will be using node js to code the application and We will use mongodb for storing the data and we can use any REST client to test those API’s.

1. Pre-requisites installation and tools:

  1. Setup the node path in your path variable so that we call use node commands from anywhere, Once Install type below command
anand@MacBook-Pro ~ $ node -v

You will get below response:

anand@MacBook-Pro ~ $ node -vv12.16.3

3. For Backend DB we will be using Mongo database, so download and install mongo database from https://docs.mongodb.com/manual/installation/, Setup the Mongod bin path in your system’s PATH Variable, and check start mongo by typing below command:

anand@MacBook-Pro ~ $ mongod

This will start your mongo server keep it running in this window.

4. An Editor:

I prefer to use Visual Studio Code, its easier and lightweight and shows colored text for an language keyword. But you can use any editor. VS code download link https://code.visualstudio.com/

now, we done with Pre-requisites lets start some basic code of node

2. Creating the Node Code:

  1. In the folder hit the below command to create package.json file automatcially that will be first step
npm init -y

3. This will create a package .json like below:

Add alt text

Add alt text

4. Now, we will be using one simple framework to design our app called express and few dependencies libraries below:

  • Express: (middleware functions) to call the methods of applications
  • Mongodb : for DB connection to mongod
  • Body-parser[for POST call]
  • Cors

5. Install above package by below commands:

npm i -g express mongodb body-parser cors

The above command will install the necessary dependencies we need for our code.

7. We will also install a small utility called NodeMon to automatically start and stop server if code changes. Command to do it:

npm i -g nodemon

After that, we can start writing code in node…!

Make Sure Your Folder structure is like below:

3. Creating first app.js file in the folder and add below code

const express = require('express');const app = express();const port = 9090;
app.get('/',(req,res) => {res.send("Hello Anand Bhagwat");})
app.listen(port,(err) => {console.log(`App is running on port ${port}`)})

Save the file and run the code from the terminal

Nodemon app.js

And Your app will listen from http://localhost:9090, hit from web browser and see something below message:

Add alt text

4. Before Adding Further Code Jump to Database:

  1. Remember you have mongod is running and the default port for that is 27017.
  2. Now open another terminal and connect to mongo server by below command:
./mongo

It will open the mongo shell:

4. Now, in mongo database we need to create one database for us to use. You can use below command to see pre-existed database:

5. Show dbs and “use DATABASE_NAME” to create new database like below:

Add alt text

You can see your new database in ready.

Add alt text

6. Now we need a table to store the data, In mongo Tables are called collections

You can see collections by connecting to db by below command first:

>use employeedatabase

Then type :

>show collections

There will be no collections create a new collection/table in Database

>db.createCollection("emp_table")

7. Now add one record in DB by below command:

>db.emp_table.insert({"emp_id":1, "emp_firstname": "Anand", "emp_lastname":"Bhagwat", "emp_salary":"10000"})

Now, our db and table is ready, now we are done from DB side

Check the record you inserted by below command:

> db.emp_table.find().pretty()

Add alt text

This completes our Backend DB part. You can add second record as well like above.

Now, Lets Switch Back to our Coding Part.

5. Coding the GET method in app.js:

const express = require('express');const app = express();const port = 9090;const mongo = require('mongodb');const MongoClient = mongo.MongoClient;const mongourl = "mongodb://localhost:27017";const bodyParser = require('body-parser');let db;let col_name='emp_table';app.use(bodyParser.urlencoded({extended:true}))app.use(bodyParser.json())app.get('/',(req,res) => {res.send("Hello Anand Bhagwat");})app.get('/employees',(req,res) => {db.collection(col_name).find({}).toArray((err,result) => {if(err) throw err;else{res.send(result)}})})MongoClient.connect(mongourl,(err,client) =>{db = client.db('employeedatabase')app.listen(port,(err) => {console.log(`App is running on port ${port}`)})})

2. In above code,

Add alt text

we have added the mongodb client and details url and created a connection to that using Mongoclient.connect. And Also added the below method:

Now, go to your browser [Firefox to see pretty format data below]

hit http://localhost:9090/employees

Add alt text

You can see above response in Postman As well:

Method GET URL:http://localhost:9090/Employees

Hit send it will return Data from our DB

Add alt text

6. Coding the POST method:

app.post('/addemployees',(req,res) => {db.collection(col_name).insert(req.body,(err,result) =>{if(err) throw err;else{res.send('Data Inserted')}})})

To see if it working we canuse POSTMAN client to check if we can add the POST request

Method POST URL http://localhost:9090/addemployees

Add json body:

[   {       "emp_id": 4,       "emp_firstname": "Rushikesh",       "emp_lastname": "Laddha",       "emp_salary": "500000000000000"   }]

Click send> It will insert new data

Check the data is added by Get Call

Add alt text

Voila… You have successfully implemented the GET and POST call :)

7. Similary add below code for DELETE and PUT method:

app.delete('/deleteemployees',(req,res) => {db.collection(col_name).remove({"emp_id":req.body.emp_id},(err,result) =>{if(err) throw err;else{res.send('Data Deleted')}})})app.put('/updateemployees',(req,res) => {db.collection(col_name).findOneAndUpdate({emp_id:req.body.emp_id},{$set:{"emp_id":req.body.emp_id,"emp_firstname":req.body.emp_firstname,"emp_lastname":req.body.emp_lastname,"emp_salary":req.body.emp_salary}},(err,result) =>{if(err) throw err;else{res.send('Data Updated')}})})

Your entire codebase is ready, In DELETE call will be deleting by using emp_id and in update employee we are finding the employee by emp_id and deleting updating that with entire body

Everything is done save the code and Test everything with PostMan now:

To Delete create an new Delete request

DELETE URL:http://localhost:9090/deleteemployees

and use below code in body to delete a record:

{   "emp_id": 2}

This will delete employe with id 2

Add alt text

Now similarly create an Update request:

And add below body:

{       "emp_id": 1,       "emp_firstname": "Anand Omprakash ",       "emp_lastname": "Bhagwat",       "emp_salary": "600000"}

This will update my emp_id firstname and salary :), Wow I got an increment… :)

Now, Structure your collection and now you are ready with Testing your own RESTful App, with CRUD Operations.

Add alt text

Happy REST API Testing folks…! :) Do share and comment for the better content add anything if I missed or if you have trouble implemeting this. Also for those who wanted my entire codebase link is here:

Link to App.js

My further plan is to Testing those with RestAssured and Creating an entire CI-CD pipeline. as part of understanding every aspect of Software DevOps Lifecycle.

I am not a Node Expert but having a little knowledge will help us in longer run…!

Thanks for Reading: Anand Bhagwat

Software QA Engineer who do QA and DevOps stuff

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store