Creating a Simple REST API with Express.js and Testing it with Postman

Creating a Simple REST API with Express.js and Testing it with Postman

A REST API (Representational State Transfer Application Programming Interface) is a type of web API, that uses HTTP protocol (Hypertext Transfer Protocol) to enable communication between a client and a server.

In this tutorial, we will create a very basic REST API using Node.js and Express.js, with the minimum number of variables in the database, to make you understand the actual concept behind it. Then, we will test the API with the help of Postman.

Postman is a popular API testing tool that allows developers to test their RESTful APIs.

Note:

I am not going to use any kind of database here too, just to keep the project simple and make you understand the idea behind it. So, I will be using a simple array of objects to store the data.

So, let's start.

STEP 1:

Create a new folder. In my case, I named it testAPI. Open it up in VS Code or any other code editor of your choice.

STEP 2:

Open the terminal and move to location where your project is stored and run the following commands:

npm init -y: This command is used to initialise a Node.js project.

npm i nodemon: Nodemon is a tool that helps you develop Node.js-based applications by automatically restarting the Node.js application when file changes in the directory are detected

npm i express: Express is a popular and lightweight web application framework for Node.js.

STEP 3:

Now, create a new file index.js in your directory and your folder structure would look like this:

image

In the index.js file type the following code:

// First we import the express module and then create an instance of express
const express = require('express')
const app = express()

// We then create a route for the root of our application
app.get('/', (req, res)=>{
    res.send('Hello World')
})

//We then listen on port 3000
app.listen(3000, ()=>{
    console.log('Server running on port 3000...')
})

Now, if you type nodemon index on your terminal and go to http://localhost:3000/ on your browser you will see: image

STEP 4:

Create a new folder namded db. Here, we will store our testdb.js, that will have our data array. In this file type:

export const testdb = () => {
    return [
        {
            id: 1,
            name: 'test1'
        },
        {
            id: 2,
            name: 'test2'
        }
    ]
}

STEP 5:

Create a new folder named routes, and then create a new file named testRoute.js in it. As of now, the folder structure looks like: image


CRUD (Create, Read, Update, Delete) operations are commonly used in REST APIs. In our API too, we will try to add new data to our database, i.e., create. POST HTTP request is used for the same. To read the data, GET HTTP request is used. To update the data, we use PUT HTTP request and finally to delete, DELETE HTTP request is used. Let's look into these requests one by one.

GET

This request will be used to read data from our database array. Here goes the code:

router.get('/db', (req, res)=>{
    //We send the json response, if an error occurs we send the error message
    try{
        res.status(200).json(db)
    } catch (err) {
        res.status(500).json({message: err.message})
    }
})

POST

This request is used to push some new data to our database array. Here goes the code:

router.post('/writeData', (req, res)=>{
    // We then create a new object to hold the data

    const newData = {
        id: db.length + 1,
        name: req.body.name
    }

    // We then push the new data to the database
    db.push(newData)
    // We then send the response
    res.status(201).json({"success": true, "message": "successfully added data", newData})
})

PUT

This request is used to update the data of a particular object, based on its id. Here goes the code:

router.put('/updateData/:id', (req, res)=>{
    // We then create a new object to hold the data
    const newData = {
        //we are reading the id from the url, and then updating the name from the body
        id: req.params.id,
        name: req.body.name
    }
     // We create a variable to hold the success status
     let success = false

     //we loop through the database to find the id, and then update the data
     for(let i=0; i<db.length; i++){
        console.log(db[i].id)
        if(db[i].id == newData.id){
            db[i] = newData
            success = true
            res.status(201).json({"success": success, "message": "successfully added data", newData})
        }
    }

    //else show that the id was not found
    if(success===false)
        res.status(404).json({"success": success, "message": "id not found"})
})

DELETE

This request is used to delete an object whose id is passed in the url. Here goes the code:

router.delete('/deleteData/:id', (req, res)=>{
    // we read the id from the url
    const id = req.params.id

    //we create a variable to hold the success status
    let success = false

    //we loop through the database to find the id, and then delete the data
    for(let i=0; i<db.length; i++){
        if(db[i].id == id){
            //we use the splice method to delete the data
            db.splice(i, 1)
            success=true
            res.status(201).json({"success": success, "message": "successfully deleted data"})
        }
    }

    //else show that the id was not found
    if(success==false)
        res.status(404).json({"success": success, "message": "id not found"})
})

Let's continue from where we left.

STEP 6:

testRoute.js file after including all those CRUD functions would look like this:

// This is a test route to test the database connection
// We then import the express module and then create an instance of express
const express = require('express')
const router = express.Router()
// We then import the database connection
const getTestDB  = require('../db/testdb')

//we then create an object to hold the database connection
const db = getTestDB()

// We then create a route to read the database
router.get('/readData', (req, res)=>{
    //We send the json response, if an error occurs we send the error message
    try{
        res.status(200).json(db)
    } catch (err) {
        res.status(500).json({message: err.message})
    }
})

router.post('/writeData', (req, res)=>{
    // We then create a new object to hold the data
    const newData = {
        id: db.length + 1,
        name: req.body.name
    }
    // We then push the new data to the database
    db.push(newData)
    // We then send the response
    res.status(201).json({"success": true, "message": "successfully added data", newData})
})

router.put('/updateData/:id', (req, res)=>{
    // We then create a new object to hold the data
    const newData = {
        //we are reading the id from the url, and then updating the name from the body
        id: req.params.id,
        name: req.body.name
    }
     // We create a variable to hold the success status
     let success = false

     //we loop through the database to find the id, and then update the data
     for(let i=0; i<db.length; i++){
        console.log(db[i].id)
        if(db[i].id == newData.id){
            db[i] = newData
            success = true
            res.status(201).json({"success": success, "message": "successfully added data", newData})
        }
    }

    //else show that the id was not found
    if(success===false)
        res.status(404).json({"success": success, "message": "id not found"})
})

router.delete('/deleteData/:id', (req, res)=>{
    // we read the id from the url
    const id = req.params.id

    //we create a variable to hold the success status
    let success = false

    //we loop through the database to find the id, and then delete the data
    for(let i=0; i<db.length; i++){
        if(db[i].id == id){
            //we use the splice method to delete the data
            db.splice(i, 1)
            success=true
            res.status(201).json({"success": success, "message": "successfully deleted data"})
        }
    }

    //else show that the id was not found
    if(success==false)
        res.status(404).json({"success": success, "message": "id not found"})
})

// We then export the router
module.exports = router

Include app.use('/', testRoute) and app.use(express.json()) in your index.js file to use this newly created route.


Testing our routes using Postman

First download Postman from the official site.

STEP 1:

Create a new collection named testAPI image

STEP 2:

Create a new GET request in this collection and name it, ReadData image image As, you can see that our data is visible after sending the request

STEP 3:

Create a new POST request named WriteData image

Now, if we read our data again: image

STEP 4:

Create a new 'PUT` request named UpdateData image

Now, if we check our data: image

STEP 5:

Create a new DELETE request named DeleteData image

Now, if we check our data: image


Some points to be noted:

  1. Include Content-Type as application/json in headers of all your requests.
  2. Also, note that the data is not being updated in our array, in the file testdb.js.

I already told you that it is a simple project to get a basic understanding of REST APIs and how you can create your own REST API. Comment if you need a detailed project on the same, that uses MongoDB too. I will make another post for that.

Here's the GitHub link for the project:

testAPI

And you can reach out to me on:

  1. Twitter
  2. Showwcase
  3. GitHub

Did you find this article valuable?

Support Swapnil Pant by becoming a sponsor. Any amount is appreciated!