Create your First REST API with Node.js, Express and MongoDB

Sudeep Timalsina
Mar 23, 2020 · 10 min read
Source: freecodecamp.org

An API is an application programming interface. It is a set of rules that allow programs to talk to each other. The developer creates the API on the server and allows the client to talk to it.

REST determines how the API looks like. It stands for “Representational State Transfer”. It is a set of rules that developers follow when they create their API. One of these rules states that you should be able to get a piece of data (called a resource) when you link to a specific URL.

Each URL is called a request while the data sent back to you is called a response.

- smashingmagazine.com

In this article we are going to develop REST API with the help of Node.js, Express and Mongodb. We will complete the CRUD operation for Bio in this article. So, let’s dive into it!

Node Version

We need to verify first that Node is installed to our machine. If not installed, first of all install node to your machine. You can check the version of node using following command.

node -v

Npm Version

Now let’s verify npm installed to the machine. You can check the version of npm using following command and install it if you haven’t done yet.

npm -v

MongoDB

We are using MongoDB as our database. MongoDB is document driven NoSql database. If you want to learn more about MongoDB and if you haven’t installed MongoDB yet, please refer to my article on MongoDB.
You can verify mongo using following command.

Start project

Now it’s time for us to start working on our project. First of all I will create a folder named MERN (refers to Mongo Express React Node) where I want to keep my node project. Then, inside MERN folder I want to give the project name and for that, I will create FirstRest folder and go inside it. Upto now we haven’t done anything rather that creating the project folder.

Initialize node.js project

Now we initialize our node.js project with npm init inside FirstRest directory.

While initiating the node.js, you will be asked different things. You only have to choose default name, add description, add author’s name and choose default License to generate package.json. If have have done any mistake, don’t worry you can change it afterwards. After completing the operation you will see the following screen.

Install Express.js

Let’s install express and setup the server. We need to run the server to make our API accessible to web browser or tools for testing the API like Postman. If you are not familiar with ExpressJS please refer to the official page. So, install express with the help of npm.

The above command will install the dependencies.

Create starter file index.js

It’s time for opening the project with the help of IDE. I will prefer vscode to run the project. You can see the node_modules folder and package.json file in the project. Since index.js is our entry file, we are going to configure the index.js file. Let’s add the following code to the index.js file on root of the project.

Run your server

Run the project with following command on project directory.

Open up the project on http://localhost:8080 on your browser and you will get the following screen.

Structuring Project

We need to create the model, controller and routes for creating our first api on node.js.

model → For managing the database layer (request and response)
controller → For defining all the http requests and handle them
routes →For defining all the endpoints

Create router

We add router.js file to the root of the project and add following code to test api.

Modify index file
Now we modify index.js, so that router is available to us. We add following code to our existing starter file index.js.

We need to stop the server once and start again in order to observe the change we have made. So, first run ctrl+c or cmd+c.
Then start the server with node index. For obtaining the changes we had made previously, we have to open the browser with http://localhost:8080/api.
Now you can see the following screen as output. Great!

Watch and restart express-server

Till now, the scenario of our project is to run the express-server every time when we make change to our project. This is really disgusting when we are working on development. So, I have one solution to avoid this kind of problem by installing nodemon. This will allow the express-server to watch the changes and restart it by itself. See how we are going to install it below.

Start with nodemon
After we have installed nodemon, let’s run our project with nodemon by using following command.

nodemon index

You can now see that express-server is restarted automatically when it detects some change in the project file. Wow, great! now our development would be faster.

Setup MongoDB

Since we are using MongoDB as our database, we need to have up and running mongoDb on our machine. If you haven’t done yet, don’t worry, consult article on MongoDB and make it running.
For running your MongoDB shell you have to enter the following command. Please make sure your MongoDB is running before you open the shell. Keep this window open for using our database.

I ran with some status=14 error while trying to start mongodb. So, I stuck for sometime and found best solution in medium and if you got stuck somewhere with same kind of error, please look at this link.
Ignore this if you have no problem in starting mongodb.

Install Mongoose and Body-Parser
We need to install Mongoose and Body-Parser. Let me explain what they are and how to install them.

Mongoose is the node.js package for modeling mongodb. It helps to handle the business logic and validation for mongodb on node.js. Learn more about Mongoose here.
Body-Parser enables app to parse the data coming from request. For eg: form data from urlencode. We need to import them in our app and use them as well.

Now install both of them using following commands.

Now we update our index.js with the mongoose and body-parser. Following is the code to be added.

Now, our complete index.js file looks like:

Now its time for use to work for our Model, Routes and Controller. For now, we are just implementing the CRUD of Bio with some fields. We are adding the bio to the database, retrieving the bio, updating it and deleting it. Let’s include following fields in our bio model.

  • name
  • email
  • phone
  • address

We will need following endpoints to run our api.

  • GET api/bio → Retrieves all the bio data
  • POST api/bio → Add new bio data
  • GET api/bio/{id} → Retrieve the single bio data
  • PUT api/bio/{id} → Update the bio data
  • DELETE api/bio → Delete the bio data

Now we going to add model and controller for performing CRUD of Bio.

Create Model

Add file named bioModel.js to the root of the project and add following lines of code to the model.

Create Routes

We now update the route.js we defined before with following lines of code to include different endpoints we discussed above.

Create Controller

We create a file with name bioController.js to the root of the project. We add following lines of code to handle different types of request and provide response according the request we get.

Demo

Now we need to open postman for testing our Api. If you have not installed postman yet and if you are on Ubuntu, please refer this link to install postman to the system. If you are in other OS, first install postman.
We are all set to test our api.

First of all let’s see what we have on our bio. Please enter http://localhost:8080/api/bio and send the GET request as shown below and you will get the response with empty list.

Let us add a data to our bio. You need to select POST as request type, navigate to body and choose the option as I have selected below. Then add the following fields and their values.

After running sending the request, we have created a new bio on our database. We add 2–3 more bios to our database as before.

Again we retrieve the data that we have on bio with GET request as follows.

For retrieving the single bio, we pass bio id the url with GET request as given below.

We are now updating the value of one of the bio with PUT request as follows.

Similarly, we can delete the bio using id as given below with DELETE request.

After deleting one of the bio, lets retrieve the remaining bios from our database as given below.

Wow! it simply worked perfectly. We did a simple CRUD of a bio with the help of Node.js, ExpressJS and MongoDB. Did you enjoy making your First Rest API with Node.js, Express and MongoDB? Let me know, if you enjoyed creating your First API with me. If you have any confusions or you got stuck somewhere please let me know in the comments below. You can also refer to my Github repository to access the project and run it directly. I will come up with more articles on MERN stack on the days to come.
Stay tuned!

wesionaryTEAM

Visionary Development Team. We ❤︎ Technology!

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

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