How to Make REST API with Node.js, Express, and MongoDB

Umang Agrawal
JavaScript in Plain English
4 min readJun 9, 2021

--

Part 1. Server connection setup

In this post, you will understand what is a REST API and learn how to make the connection setup for the API in Node.js with MongoDB Atlas.

By: umang

Firstly, what is Restful API?

REST(REpresentational State Transfer) is an architectural style or pattern that defines the set of constraints for developing web applications. Restful APIs are a way of accessing the data or services in a simpler way.

When a request is made to the endpoint, it transfers the representation of the state of resources to the endpoint, and the response is given back in one of these formats: JSON (most commonly used), HTML, PHP, Xlt, or simple text.

What makes an API Restful?

  • It should not store the information of the client on the server.
  • Client-server architecture with request managed through http.
https://www.altexsoft.com/blog/rest-api-design/

Requirements before starting

  • Your preferred IDE (VSCode, Atom, etc)
  • Node.js installed (check by typing node -v in terminal)
  • MongoDB on the PC or MongoDB Atlas (setup your account and make a cluster), the latter is preferred.
  • API testing tool like Postman or any of these alternatives.

Firstly, we will initialize the Node.js project. To initialize, make a new folder for the project and open that folder in VSCode and type the below command in the terminal:

npm init (and follow the process)
or
npm init --yes (put this flag to make project with default setting)

Now you will be able to see the package.json file in the folder. Go to that file and change a few lines of code:

1. "main": "server.js",2. "scripts": { "start": "nodemon server.js" }

Go to the terminal now and install a few dependencies by writing the below code:

npm install express nodemon cors body-parser mongoose dotenv

All the dependencies are necessary and I will tell their use as we move ahead. nodemon will restart your server automatically after code changes.

  1. Make .env file in the main dir from here we will fetch our secret keys, password, the port number so that others can’t access it (don’t push this file on GitHub). Write the below code in the .env file:
PORT = 5000

2. Now make a server.js file in the same directory and write the following code which will create our server:

const http = require('http')
const app = require('./app')
const port = process.env.PORT || 3000
const server = http.createServer(app)
server.listen(port)

3. Make app.js in the same directory. Over here, we will define the basic routes of the API, and connect with our MongoDB database. You can think of this file as your main entry to the API files. Now start writing the code in that file:

const express = require('express')
const app = express()
const cors = require('cors')
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
require('dotenv/config')

Note: Body-parser is a middleware used to parse the body of the upcoming request, dotenv is used to fetch the env variables, cors is also a middleware use to enable cors,mongoose is object data modelling library for mongodb and nodejs. 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…🔗

Now to connect with MongoDB, go to your MongoDB Atlas cluster and get the database connection code and paste it in the dotenv file like this:

DB_CONNECTION = mongodb+srv://Yourname:password@cluster0.pi2rv.mongodb.net/dbname?retryWrites=true&w=majorityNote: Replace all the bold word respectively:
your username (umang)
password (1234)
Database name (Shop)

Now, go to app.js and write the code for connection with the db, and finish up the connection setup.

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
# Defining all the http header and the request options
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, PATCH, DELETE')
return res.status(200).json({})
}
next();
});
mongoose.connect(
process.env.DB_CONNECTION,
{useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log('connected to database')
})
mongoose.Promise = global.Promise
app.use((req, res, next) => {
res.status(200).json({message: "It works"});
})

Now our setup is done, go to the terminal in the vscode and type

nodemon server.js 
// it will run a server and database connection will be made

Test it by going to http://localhost:5000. It should reply It works.

Hurray! You have done the basic connection setup for your REST API in Node.js, Express, and MongoDB.

Stuck with an error? No problem! Leave a comment and I will definitely try to solve it. Otherwise, mail me at 25umangagarwal@gmail.com or connect with me on LinkedIn.

Part 2. Making API Endpoints for /get request

More content at plainenglish.io

--

--