How to Build RESTful API With NodeJs, ExpressJs and MongoDb Atlas

Anshul Borawake
The Startup
Published in
6 min readJan 20, 2021

RESTFul APIs have been around for sometime now. At the time of this write-up it is practically impossible for you to be a software developer without having to create and use one or more APIs.

API is an acronym for Application Programming Interface which has become an integral part of software development. “It is a set of of clearly defined methods of communication between various components” — Wikipedia.

RESTFul APIs, on the other hand, are APIs that conform to the REST architectural style. REST refers to Representational State Transfer which “is an architectural style that defines a set of constraints and properties based on HTTP”.

You can learn more about JSONAPI specifications, examples and implementation here. JSON is simply Javascript Object Notation.

In this tutorial, we build a simple API using ExpressJs and MongoDb with CRUD functions for Users and respective posts.

Required applications

  • NodeJS
  • PostMan
  • MongoDb Atlas ( Cloud Storage )
  • IDE

Let’s get started…

Creating Project File

// Navigate to the any location lets say Desktop
cd Desktop
// Create directory for your new project RestHub
mkdir restAPI
// Navigate into the directory
cd restAPI
Navigate to Desktop and Create Project folder restAPI

Initialize NodeJs project with npm init follow the wizard to setup the project.

Time to Install Express, Nodemon, CORS and Setup Server installation

We need to run a web server in order to make our API endpoint accessible to the browser or a tool like PostMan, we shall be using ExpressJS to achieve this. If you are not familiar with ExpressJS head to the official website to learn more, otherwise let’s keep going. With npm we install Express in our project with this command

// Installation of required packages
npm i express cors bcryptjs body-parser dotenv joi mongoose --save
// Installation of developer dependency
npm i nodemon --save-dev

It will take a while to complete the installation depending on your connection speed but in the end expressJs and its dependencies will be installed as below.

Enough of all these installations, wizards and configurations. We need to start writing code now. Time you open your preferred IDE, mine is Visual Studio Code.

Use your preferred IDE to open the project directory and create a file app.js and modify package.json as shown below
Note: check “scripts”

check scripts => start script. Update it !!

You can see one directory node_modules and one file package.json. Package.json store the nodeJs project configuration including dependencies. You can see the just installed expressjs -v4.17.1 under dependencies. Installed node packages are located in node_modules and we should not modify anything in that directory rather we should exclude with gitignore when we are pushing to a remote repository. In our package.json, we defined app.js as our app’s entry point. We need to create that file now and setup our web server.

Lets Start Coding

App.js

In you IDE, create a file app.js and add this code…

Code Explanation

  • We are creating routes and using app.use('route_name', routeVariable)
  • mongoose.connect() is used to connected to the MongoDB Atlas cloud server.
  • app.listen() is used to start local server at PORT:3000

Save the file and run npm starton the terminal window. You should get this

Head to http://localhost:3000on your browser and you should see…

Create Model Schema for Database

USER Schema

./models/User.js

Note: We are creating user schema, this schema is the information our database will be storing at the server.

  • name: Username of the specific user.
  • email: User email which we will verified using joi validation, type String and required true (meaning compulsory)
  • password: User password which we will encrypt using by bcryptjs , type String and required true
  • date: Automatically, assigned at the time of creation of post.

POST Schema

./models/Post.js

Note: We are creating post schema, this schema is the information i.e., a post will have the following -

  • userID: The id of the user who created the post.
  • title: Title of the post, type String and required true (meaning compulsory)
  • description: Description for the post, type String and required true
  • date: Automatically, assigned at the time of creation of post.

User Login and Registration Validation

Validating user information before hitting the api

Validation.js

Note: We are using Joi

  • joi is used to validate created object from the with the required fields of the information we are taking as input.
  • After creating the object we are using the JoiObject.validate(data) function to validate the our accepted data.

Create Routes to Access the Models and Database

User Routes

./routes/user.js

What are we doing here??

  • We are creating POST method to send registration and login requests to server and before sending data to the database we are validating the information / data
  • If any error is generated we are returning the response and the error, that was causing the issue.
  • For the password, during registration we are encrypting the password using hash salt, and during login we are encrypting the login password and comparing with the hashed password in the database.
  • Finally, api to delete specific user.

We will implement the following endpoints:

  • POST /user/register create new user
  • POST /user/login login to existing user
  • DELETE /user/{uid}/only delete only the user & not posts linked with user
  • DELETE /user/{uid}/all delete all data including posts about the user

Post Routes

./routes/posts.js

Finally, the last endpoint and main end point “posts” :

  • We are creating POST method to register a post for that user.
  • Secondly, we are using GET method to fetch all the posts details or a specific post details from the server.
  • Thirdly, we are using PATCH method to update the “Title” of the post.
    You can modify the code to update the “Description” also.
  • Finally, method to DELETE the post from the user records.
  • Every time we are using UID to link user to their specific posts.

We will implement the following endpoints:

  • POST /posts/{uid}create new post for the user
  • GET /posts/{uid}get all posts related to the user
  • GET /posts/{uid}/{postID}get specific post related to the user
  • PATCH /posts/{uid}/{postID}update the post related to that user using uid for validation and postID to update post title
  • DELETE /posts/{uid}/{postID}delete all data regarding the posts about the user

POSTMAN ScreenShots

USERS ROUTE

User API

POSTS ROUTE

Post API Method

NOTE: Don’t forget to replace your own MONGODB-ATLAS-KEY in .env file

Useful Links:

--

--

Anshul Borawake
The Startup

React Developer | React Native Developer | Machine Learning | AI Enthusiast | Self-Learner | ACES — Vice-President