Creating a Simple REST API with ExpressJS and  Postman

Creating a Simple REST API with ExpressJS and Postman

Introduction

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 basic REST API using Node.js and Express.js, with the dummy product data 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 dummy product data.

So, let's start.

STEP 1:

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

STEP 2:

Open the terminal and move to a 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 a 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:

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 named data. Here, we will store our Product.json will have our data array. In this file type:

Here you can paste the dummy product json data.

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 this :

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 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 :

// Endpoint to render product list in HTML format
server.get("/", (req, res) => {
  const renderedProducts = products.map((product) => {
    const productHTML = indexTemplate
      .replace("**thumbnail**", product.thumbnail)
      .replace("**title**", product.title)
      .replace("**description**", product.description)
      .replace("**price**", product.price)
      .replace("**rating**", product.rating);
    return productHTML;
  });

  const finalHTML = renderedProducts.join("");
  res.send(finalHTML);
});

// GET endpoint to retrieve all products
server.get("/products", (req, res) => {
  res.json(products);
});

server.get("/products/:id", (req, res) => {
  const id = parseInt(req.params.id);
  const product = products.find((p) => p.id === id);
  if (product) {
    res.json(product);
  } else {
    res.status(404).json({ message: "Product not found" });
  }
});

POST

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

server.post("/products", (req, res) => {
  const newProduct = req.body;
  newProduct.id = products.length + 1; // Assign a new ID
  products.push(newProduct);
  res.status(201).json(newProduct);
});

PUT

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

// PUT endpoint to update a product by ID
server.put("/products/:id", (req, res) => {
  const id = parseInt(req.params.id);
  const productIndex = products.findIndex((p) => p.id === id);
  if (productIndex !== -1) {
    products[productIndex] = { ...req.body, id }; // Preserve the existing ID
    res.status(202).json({ message: "Product updated successfully" });
  } else {
    res.status(404).json({ message: "Product not found" });
  }
});

DELETE

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

// DELETE endpoint to delete a product by ID
server.delete("/products/:id", (req, res) => {
  const id = parseInt(req.params.id);
  const productIndex = products.findIndex((p) => p.id === id);
  if (productIndex !== -1) {
    products.splice(productIndex, 1);
    res.status(202).json({ message: "Product deleted successfully" });
  } else {
    res.status(404).json({ message: "Product not found" });
  }
});

Let's continue from where we left off,

STEP 6:

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

const fs = require("fs");
const express = require("express");
const server = express();

server.use(express.json());
server.use(express.static("public"));

// Load product data from JSON file
const rawData = fs.readFileSync("products.json", "utf-8");
const data = JSON.parse(rawData);
let products = data.products;

// Read the index.html template
const indexTemplate = fs.readFileSync("index.html", "utf-8");

// Endpoint to render product list in HTML format
server.get("/", (req, res) => {
  const renderedProducts = products.map((product) => {
    const productHTML = indexTemplate
      .replace("**thumbnail**", product.thumbnail)
      .replace("**title**", product.title)
      .replace("**description**", product.description)
      .replace("**price**", product.price)
      .replace("**rating**", product.rating);
    return productHTML;
  });

  const finalHTML = renderedProducts.join("");
  res.send(finalHTML);
});

// POST endpoint to add a new product
server.post("/products", (req, res) => {
  const newProduct = req.body;
  newProduct.id = products.length + 1; // Assign a new ID
  products.push(newProduct);
  res.status(201).json(newProduct);
});

// GET endpoint to retrieve all products
server.get("/products", (req, res) => {
  res.json(products);
});

// GET endpoint to retrieve a specific product by ID
server.get("/products/:id", (req, res) => {
  const id = parseInt(req.params.id);
  const product = products.find((p) => p.id === id);
  if (product) {
    res.json(product);
  } else {
    res.status(404).json({ message: "Product not found" });
  }
});

// PUT endpoint to update a product by ID
server.put("/products/:id", (req, res) => {
  const id = parseInt(req.params.id);
  const productIndex = products.findIndex((p) => p.id === id);
  if (productIndex !== -1) {
    products[productIndex] = { ...req.body, id }; // Preserve the existing ID
    res.status(202).json({ message: "Product updated successfully" });
  } else {
    res.status(404).json({ message: "Product not found" });
  }
});

// PATCH endpoint to partially update a product by ID
server.patch("/products/:id", (req, res) => {
  const id = parseInt(req.params.id);
  const productIndex = products.findIndex((p) => p.id === id);
  if (productIndex !== -1) {
    products[productIndex] = { ...products[productIndex], ...req.body };
    res.status(202).json({ message: "Product updated successfully" });
  } else {
    res.status(404).json({ message: "Product not found" });
  }
});

// DELETE endpoint to delete a product by ID
server.delete("/products/:id", (req, res) => {
  const id = parseInt(req.params.id);
  const productIndex = products.findIndex((p) => p.id === id);
  if (productIndex !== -1) {
    products.splice(productIndex, 1);
    res.status(202).json({ message: "Product deleted successfully" });
  } else {
    res.status(404).json({ message: "Product not found" });
  }
});

server.listen(8000, () => {
  console.log("Server is running on port 8000");
});

Note :

You have to also create index.html like these :

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Product Cards</title>
    <style>
        body {
            margin: 0;
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
        }

         .card {
            border: 1px solid #ccc;
            border-radius: 8px;
            padding: 10px;
            background-color: white;
            display: flex;
            flex-direction: column; 
            align-items: center;
            text-align: center;
            box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);
            margin: 10px;
        }

        .thumbnail {
            width: 80px;
            height: 80px;
            border-radius: 4px;
            object-fit: cover;
            margin-bottom: 10px;
        }

        .title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 5px;
        }

        .description {
            font-size: 14px;
            color: #666;
            margin-bottom: 5px;
        }

        .price {
            font-size: 16px;
            font-weight: bold;
            color: #008CBA;
            margin-bottom: 5px;
        }

        .rating {
            font-size: 14px;
            color: #007bff;
        }
    </style>
</head>

<body>
    <div class="card">
        <img class="thumbnail" src="**thumbnail**" alt="Mobile Thumbnail">
        <div class="details">
            <div class="title">**title**</div>
            <div class="description">**description**</div>
            <div class="price">**price**</div>
            <div class="rating">&#9733; **rating** (1000+ ratings)</div>
        </div>
    </div>
</body>

</html>

After that run the code and check all the route that is working or not like this :

http://localhost:8000/

http://localhost:8000/products

http://localhost:8000/products/1


Testing our routes using Postman and performing crud operations

First download Postman from the official site.

STEP 1:

Create a new collection named TestAPI

STEP 2:

Create a new GET the request and paste the localhost Url here: -

and Click on send button, then you will be able to see the requested URL data.

As you can see that our data is visible after sending the request

STEP 3:

Create a new POST request and paste the new data in the body part to add new data.

Here, you can see that I added the new product named "I phone 15".

Now if we want to update any data for the id:31, How we can update the data?

We can update the data using PUT operation.

STEP 4:

Create a new PUT request to update the data

Here you can see that I have updated the price, discount percentage and the rating forid:31 .

Now, you can see the updated data below,

STEP 5:

Create a new DELETE request to delete the data,

Conclusion:

In this tutorial, we walked through the process of creating a basic REST API using Node.js and Express.js. We started by setting up the project, installing necessary dependencies like Nodemon and Express, and creating API routes for handling CRUD operations (Create, Read, Update, Delete).

By following the steps outlined in this tutorial, you've gained an understanding of how to:

  • Initialize a Node.js project and install the required packages.

  • Set up an Express server to handle HTTP requests.

  • Create routes for various CRUD operations, such as retrieving data, adding new entries, updating existing data, and deleting entries.

  • Use dummy data to simulate interactions with a database.

  • Test your API routes using Postman to verify their functionality.

We hope this guide has empowered you to Rest API using Express.js. If you have any questions or would like to share your experiences, feel free to reach out. Happy coding!

Got questions or insights to share? Drop a comment below — I'd love to hear from you!

Keep coding,

Raja Kumar

P.S. If you missed my previous posts, catch up on my backend development journey and stay updated.

Did you find this article valuable?

Support Raja's blog by becoming a sponsor. Any amount is appreciated!