Nairobi, Kenya

Node,Express and MongoDB REST API

Node,Express and MongoDB REST API

Hi All, In this article today we are going to build a REST API using node, express and MongoDB.

  • Express is a lightweight web framework for node
  • MongoDB is a nosql database for storing our records
  • Node is used as a JavaScript run-time environment.

API

An API (Application Program Interface) is a connection between computer programs. APIs create a communication protocol between the back end and the front end of a program.

In other words it is the code that governs the access point(s) for the server.

A REST API is an architectural style for an application program interface (API) that uses HTTP requests to access and use data,

These include the CREATE / READ / UPDATE and DELETE operations

That is one can read, update, create and delete a resource.

Prerequisites

  • NodeJS -Back end Language Make sure Node is installed on your PC download
  • MongoDB – Data Base
  • Postman – Tool used to test our API download

Dependencies Used

  • no-demon
  • express
  • mongoose

So today we are going to build a REST API that captures some records, we are going to have the name and email fields in the record,In this API one can add , retrieve,update and delete a record.

MongoDB set Up

In our step number one lets set up our database , we are going to set up our database in the cloud, we are not going to store our records locally; Follow this guide to jump start off with MongoDB

1. File and Directory Set Up

Open the command line then navigate to your default folder and then make a directory called node_rest_api as shown below

mkdir node_rest_api

Change the working directory and then Initialize the the package.json file where our dependencies will be stored

cd node_rest_api 
npm init -y

after running npm init -y a file with the structure below will be generated.

  "name": "node_rest_api",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Lets install our dependencies we need mongoose,express and nodemon.

npm i mongoose express nodemon

We also need three additional folders that is our routes,models and database folders type the following in the command line, Type them one by one separately

mkdir db
mkdir routes
mkdir models

In the folders created we also need some additional files to write our program, in each folder we will have one additional .js file write the following in the command line separately

touch models/user.js
touch routes/user.js
touch db/db.js

Finally lets create our server file type

touch server.js

Lets create our server and see the results in the browser In the server.js file add the codes below

const express = require('express')
const app = express()
app.get('/', (req,res)=>{
    res.send('my app')
})

const port = 3000;
app.listen(port, ()=> console.log(`listening on ${port}`))

PACKAGE.JSON Edit the package.json file and add the code below, the reason for this is that we wont be starting our server every time we make a change in our file but instead the nodemon dependency we installed earlier will do the work for us. Edit the scripts line and then add the following lines

"scripts": {
    "start": "nodemon server.js"
  }


//the whole file

{
  "name": "node_rest_api",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "nodemon server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "mongoose": "^5.13.3",
    "nodemon": "^2.0.12"
  }
}

to start your server type the following on the command line

npm start

Open your browser on localhost:3000 and you will see the message my app

Upon successful completion the following messages will be displayed on the terminal / command line ,

listening on 3000 so we wont be refreshing every time we make a change on our code since nodemon has everything for us.

2. Data Base Connection

Having followed the guide above and hoping that you have your first MongoDB database on atlas Lets have the following code on the db.js file

const mongoose = require("mongoose");

mongoose.connect(
    "mongodb+srv://ian:<password>@ian.qfm7u.mongodb.net/Fistdatabase?retryWrites=true&w=majority", 
    { useNewUrlParser: true, useUnifiedTopology: true,useCreateIndex: true  }
)
 .then(console.log('connected succesfully'))
 .catch(err=> console.log(err))

POINT TO NOTE:

Due to security reasons kindly remember to replace your password and Database name on the above file, on the place named password and Firstdatabase. lets import it in our server.js file, by writing the code below just below app

require('./db/db')

Checking on the console the following messages should be displayed

connected successfully
listening on 3000

Good work done you have successfully connected your database.

3. ROUTES

Lets define the route for our API, In our routes/user.js file add the codes below

const express = require('express')
const router = express.Router()

router.get('/', (req,res)=>{
    res.send('Hey Mango')
})

module.exports = router`

Import the file in the server.js then tell our app to use it as a middleware

const userRoute = require('./routes/user')

app.use('/api', userRoute) //type before the port line

Open the browser and type localhost:3000/api upon success a message Hey Mango will be displayed on the interface, Good your route is now working.

4. MODEL

In our models we only need to store two filed that is the name and email, lets set up by writing the codes below In our models/user.js

const mongoose = require('mongoose')

const dataSchema = new mongoose.Schema({
    name:{
        type: String,
        required: true
    },
    email:{
        type: String,
        required: true
    }
})

module.exports = mongoose.model('Data' , dataSchema)

Then import it in our routes/user.js file as follows

const Data = require('../models/user')

since we are going to use data in json() format lets add the code below,

The express. json() is a method inbuilt in express to recognize the incoming Request Object as a JSON Object.

app.use(express.json())

we are done now lets write our api logic

5. Creating a user

In creating a User, we will use the post method,

The Post request creates a new instance of a data of the model we had created.

The req.body is used to access data in JSON from the client side.

The database automatically assigns an ID to the new blog post.

Successful save will be seen using status 201 and the data sent to the postman console .

On failure a status message 400 will be displayed.

//create new Data

router.post('/', async (req,res)=>{
    const data = new Data(req.body)
    try{
        await data.save()
        res.status(201).send(data)
    }
    catch(err){
        res.status(400).send(err)}
})

Having installed postman open it up and test your app, type localhost:3000/api then configure it to accept a POST request

Then try keying in new data in the body section configured to accept a data in JSON format as follows, upon success the data will be sent in the console

Then send the data upon success your the postman console should read as below

Good work done

Follow the same procedure and then add some five record which will be used in the subsequent systems

6. Getting all data

To get all the data in our database we are going to use the mongoose method called Find to get all our data in json() format type, upon success the data will be sent to the console but on failure a status 500 will be displayed and the error sent in the postman console

//getting all Data
router.get('/',async (req,res)=>{
    try{
        const data= await Data.find({})
        res.send(data)
    } catch(err){
        res.status(500).send(err) }
    })

Go to localhost:3000/api on postman then configure it to accept a GET request as follows then send to get all the records in the console upon success

7. Retrieving a user By id

In here we will add the id field in our route, we will use the mongoose method findById to retrieve our data according to the id, the req.params.id contains the properties mapped to the named route,if the user does not exist a 404 status error will be displayed, upon success a status 200 will be displayed, but on failure a status 500 will be displayed and the error sent in the postman console

see below

//GET BY ID
router.get('/:id', async (req,res)=>{
    try{
        const data = await Data.findById(req.params.id)
        if(!data){
            return res.status(404).send()
        }
        res.status(200).send(data)
    }catch(err){
        res.status(500).send(err)
    }
})

Copy one user id the paste it after the localhost:3000/api/ it should be localhost:3000/api/id then send to get the user in the console in my case i have

8. Update a User

In here we are going to use the patch method, we will retrieve the user by id then use req.body to get all the required filed and req.params.id containing properties mapped to the named route, we will include id in our route then use the mongoose method findByIdAndUpdate,upon success the data will be sent to the console but on failure a status 422 will be displayed and the error sent in the postman console

//UPDATE USER

router.patch('/:id', async (req,res)=>{
    let body = req.body
    let id = req.params.id
    try{
        const data  = await Data.findByIdAndUpdate(id, body)
        res.send(data)
    }catch(err){
        res.status(422).send(err)
    }
})

Configure the postman to use the patch method Copy one user id the paste it after the localhost:3000/api/ it should be localhost:3000/api/id , update then send the data twice to get the user in the console and see what happens , in my case i have i have updates my user one

9. Delete a user

In here we are going to use the delete method, we will retrieve the user by id and then use req.params.id containing properties mapped to the named route, we will include id in our route then use the mongoose method findByIdAndDelete,when a user does not exist a status 404 will be sent , upon success the data will be sent to the console but on failure a status 500 will be displayed and the error sent in the postman console

//DELETE USER

router.delete('/:id', async (req,res)=>{
    try{
        const data = await Data.findByIdAndDelete(req.params.id)
        if(!data){
            res.status(404).send()
        }res.send(data)
    }catch(err){
        res.status(500).send()
    }
})

Configure the postman to use the delete method Copy one user id the paste it after the localhost:3000/api/ it should be localhost:3000/api/id , delete a user then get all users to see the remaining.

Good we have made our Node,Express and MongoDB REST API keep practicing more

source code

Happy Coding