How To Make A REST API With Node Js, Express And MongoDB

How To Make A REST API With Node Js, Express And MongoDB

Avatar photoPosted by

Introduction:

Good day, fellow dev, today I will be showing you how to make REST API with ExpressNode Js, and MongoDBREST API is used for communication between client and server. REST stands for representational state transfer and API stands for application programming interface. REST API also known as RESTful API is a type of API that uses the REST architectural style, an API uses REST if it has these characteristics:

  • Client-Server – The communication between Client and Server.
  • Stateless – After the server completes an HTTP request, no session information is retained on the server.
  • Cacheable – Response from the server can be cacheable or noncacheable.
  • Uniform Interface – These are the constraints that simplify things. The constraints are Identification of the resources, resource manipulation through representations, self-descriptive messages, and hypermedia as the engine of the application state.
  • Layered System – These are intermediaries between client and server like proxy servers, cache servers, etc.
  • Code on Demand(Optional) – This is optional, the ability of the server to send executable codes to the client like Java applets or JavaScript code, etc.

Express.js – commonly referred to as Express, is a minimal and flexible web application framework for Node.js. It provides a robust set of features to develop web and mobile applications. Express.js simplifies the process of building web servers and APIs in Node.js by providing a powerful and easy-to-use set of features.

Node.js – is an open-source, cross-platform JavaScript runtime environment that allows developers to run JavaScript code outside of a web browser. It uses the V8 JavaScript engine from Google Chrome to execute code, making it possible to use JavaScript for server-side scripting.

MongoDB – is a popular open-source NoSQL database program. It is classified as a document-oriented database, belonging to the family of NoSQL databases, which do not use the traditional table-based relational database structure used in SQL databases like MySQL and PostgreSQL.

Prerequisite:

  • MongoDB
  • Node >= 18.20.2

File Structure Preview:

image 45 Binaryboxtuts

Step 1:Initialize Node.js project

Create a folder named express-api, go into the newly created folder and open your terminal or cmd, and run this command:

npm init -y

Running npm init -y initializes a new Node.js project in the current directory using default values for package.json fields, without requiring user input. The -y flag stands for “yes,” which means it automatically accepts all defaults. This command is useful for quickly setting up a new project without having to manually enter information for each field in the package.json file.

Step 2: Install Packages

After initializing a node.js project, let’s install the packages that we will be using:

npm install express
npm install dotenv
npm install cors
npm install mongoose
  • express – Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for building web applications and APIs. It is designed to make the process of creating server-side applications in Node.js simpler and more efficient.
  • dotenv – is a popular npm package that loads environment variables from a .env file into process.env, making it easy to manage configuration settings in Node.js applications.
  • cors – CORS (Cross-Origin Resource Sharing) middleware package in a Node.js project. CORS is a security feature implemented by web browsers to prevent unauthorized access to resources hosted on a different origin (domain, protocol, or port) than the one making the request.
  • mongoose – Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js, designed to work in an asynchronous environment. It provides a straightforward schema-based solution to model your application data and handle interactions with a MongoDB database.

Then let’s install the nodemon package, if you have already installed nodemon you can skip this.

  • nodemon – is a utility that monitors changes in your Node.js application files and automatically restarts the server whenever a change is detected. This eliminates the need to manually stop and restart the server every time you make changes to your code, making the development process more efficient and productive. Nodemon is particularly useful during the development phase of a Node.js application when you frequently make changes to your code and want to see the changes reflected immediately without having to restart the server manually.
npm install -g nodemon 

Running npm install -g nodemon installs the Nodemon package globally on your system. The -g flag stands for “global,” which means Nodemon will be installed in a location accessible system-wide, rather than being installed locally in a specific project directory.

Step 3: Setup Express Application

Create a file inside our root folder, name the file server.js, and add these lines of codes:

server.js

require('dotenv').config()

const express = require('express')
const mongoose = require('mongoose')
const cors = require('cors')
const projectRoutes = require('./routes/projectApi')

// express app
const app = express()

// middleware
app.use(express.json())
app.use(cors())
app.use((req, res, next) => {
  console.log(req.path, req.method)
  next()
})

// routes
app.use('/api/projects', projectRoutes)

// connect to mongodb
mongoose.connect(process.env.MONGO_URI)
.then(() => {
    console.log('connected to database')
    // listen to port
    app.listen(process.env.PORT, () => {
        console.log('listening for requests on port', process.env.PORT)
    })
})
.catch((err) => {
    console.log(err)
}) 

In an Express.js application, the entry point is typically the main file where you initialize the Express server and define its configurations, routes, and middleware. This main file is commonly named server.js or app.js, but it can be named anything you prefer.
The entry point file is where you set up your Express application by importing the necessary modules, creating an instance of Express, defining routes, applying middleware, and starting the server. It’s the starting point of your application’s execution.

Step 4: Update package.json

Add this line on the scripts field “dev”: “nodemon server.js”. The scripts field defines a set of commands that can be executed via npm. These scripts provide shortcuts for common development tasks, such as starting the server, running tests, building the project, etc.

package.json

{
  "name": "express-api",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "nodemon server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "dotenv": "^16.4.5",
    "express": "^4.19.2",
    "mongoose": "^8.3.2"
  }
}

Step 5: Setup Environment Variables

Create a .env file, and add the environment variables.

.env

PORT=4000
MONGO_URI=mongodb://127.0.0.1:27017/express_rest_api
  • PORT – port number on which the server should listen for incoming HTTP requests
  • MONGO_URI – refers to the Uniform Resource Identifier (URI) used to connect to a MongoDB database. It contains information such as the protocol, hostname, port, database name, and optionally authentication credentials.

You can get the url when you open the MongoDBCompass:

image 39 Binaryboxtuts

Sample .env

PORT=4000
MONGO_URI=mongodb://127.0.0.1:27017/express_rest_api

Step 6: Create A Model

Create a folder named models inside our root folder,  and inside it create a file named projectModel.js and add these lines of code.

models\projectModel.js

const mongoose = require('mongoose')

const Schema = mongoose.Schema

const projectSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  description: {
    type: String,
    required: true
  },

}, { timestamps: true })

module.exports = mongoose.model('project', projectSchema)

Step 7: Create A Controller

Create a folder named controllers inside our root folder,  and inside it create a file named projectController.js and add these lines of code.

controllers\projectController.js

const Project = require('../models/projectModel')
const mongoose = require('mongoose')

// get list of projects
const getProjects = async (req, res) => {
  const projects = await Project.find({}).sort({createdAt: -1})

  res.status(200).json(projects)
}

// create a new project
const createProject = async (req, res) => {
    const {name, description} = req.body
  
    // add to the database
    try {
      const project = await Project.create({ name, description })
      res.status(200).json(project)
    } catch (error) {
      res.status(400).json({ error: error.message })
    }
  }

// get specific project
const getProject = async (req, res) => {
  const { id } = req.params

  if (!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(404).json({error: 'No project found for id ' + id})
  }

  const project = await Project.findById(id)

  if (!project) {
    return res.status(404).json({error: 'No project found for id ' + id})
  }

  res.status(200).json(project)
}

// update a project
const updateProject = async (req, res) => {
    const { id } = req.params
    const {name, description} = req.body
    if (!mongoose.Types.ObjectId.isValid(id)) {
        return res.status(404).json({error: 'No project found for id ' + id})
    }

    const project = await Project.findOneAndUpdate({_id: id}, {name, description}, {returnOriginal: false})

    if (!project) {
      return res.status(404).json({error: 'No project found for id ' + id})
    }

    res.status(200).json(project)
}
  
// delete a project
const deleteProject = async (req, res) => {
    const { id } = req.params
  
    if (!mongoose.Types.ObjectId.isValid(id)) {
      return res.status(404).json({error: 'No project found for id ' + id})
    }
  
    const project = await Project.findOneAndDelete({_id: id})
  
    if(!project) {
      return res.status(404).json({error: 'No project found for id ' + id})
    }
  
    res.status(200).json({message: 'Project deleted.'})
  }
  


module.exports = {
  getProjects,
  createProject,
  getProject,
  updateProject,
  deleteProject
}

Step 8: Create A Route

Create a folder named routes inside our root folder, and inside it create a file named projectApi.js and add these lines of code.

routes\projectApi.js

const express = require('express')
const {
    getProjects,
    createProject,
    getProject,
    updateProject,
    deleteProject
} = require('../controllers/projectController')


const router = express.Router()

// get list of projects
router.get('/', getProjects)

// create a new project
router.post('/', createProject)

// get specific project
router.get('/:id', getProject)

// update a project
router.patch('/:id', updateProject)

// delete a project
router.delete('/:id', deleteProject)



module.exports = router

Step 9: Start the Express App

Run this command to start the Express App:

npm run dev

After successfully running your app, the base url of our app will be:

http://localhost:4000

Test the API:

We will be using Insomia for testing our API, but you can use your preferred tool.

POST Request – This request will create a new resource.

image 40 Binaryboxtuts

GET Request – This request will retrieve all the resources.

image 41 Binaryboxtuts

GET Request (with id) – This request will retrieve a particular resource.

image 42 Binaryboxtuts

PATCH Request  – This request will update a resource.

image 43 Binaryboxtuts

DELETE Request – This request will delete a resource.

image 44 Binaryboxtuts