Tech

How to set up API endpoint for a simple project in Node.js?


The API endpoint is a point at which an application program interface (API) connects with the software program.
API’s work by sending requests for information from a web application or web server and receiving a response.

api endpoint

Nowadays it is common for online applications to have a public API endpoint, they are used by developers to integrate features like chats, logins, payments, etc…

The Standard they use for this is called Representational State Transfer (REST).

REST stands for representational state transfer and was created by computer scientist Roy Fielding.

REST manipulate data with CRUD (CREATE-READ-UPDATE-DELETE) operations:

  • POST (create data)
  • GET (retrieve data)
  • PUT (create or replace data)
  • PATCH (update data)
  • DELETE (delete data)


So in this tutorial, we will build a simple REST API backend using Node.js with POST, PATCH, GET and DELETE operations.

Creating the Products Module

We will be using Mongoose, an object data modeling library for MongoDB.

First, we need to create the Mongoose schema in /products/models/products.model.js:

const mongoose = require("mongoose");

const productSchema = new Schema({
  name: String,
  description: String,
  price: String,
  currency: String,
});

module.exports = mongoose.model('Products', productSchema);

“POST” product data

Let’s start with the “create product” operation by defining the route in routes/products.config.js:

const ProductsController = require('../controllers/products.controller');

app.post('/products, [
  ProductsController.create
]);

The ProductsController object is imported from our controller defined in /products/controllers/products.controller.js:

const jsend = require("../utils/jsend");
const ProductModel = require("../models/product.model");

exports.create = (req, res) => {
    const newProduct = new ProductModel(req.body);

    newProduct.save((err, product) => {
        if (err) {
            return res.status(500).send(
                jsend(500, {
                    message: "Some error occured and a new Product could not be created!",
                })
            );
        }

        res.status(201).send(
            jsend(201, {
                product._id,
            })
        );
    });
};

At this point, we can test our Mongoose model by running the server (npm start) and sending a POST request to /products with some JSON data:

{
  "name" : "Iphone 12",
  "description" : "Used Iphone for sale",
  "price" : "500",
  "currency" : "USD"
}

There are several tools you can use for this. Postman is a popular GUI tool, and curl is a common CLI choice.

At this point, the result of a valid post will be id from the created product: 

{ "2c03c6d94312bf24069e38b1" }

“Create” operation of the product is done.

“GET” product data by id

Now we need to see if the product exists. For that, we are going to implement the “get product by id” feature for the following endpoint: products/:productId.

First, we create a route in /routes/product.config.js:

app.get('/products/:productId', [
    ProductsController.getById
]);

Then, we create the controller in /products/controllers/products.controller.js:

exports.getById = (req, res) => {
  ProductModel.findOne({ _id: req.params.productId })
    .then((product) => {
      if (!product) {
        return res.status(404).send(
          jsend(404, {
            message: "Product not found!",
          })
        );
      }

      res.status(200).send(
        jsend(200, {
          product,
        })
      );
    })
    .catch((err) => {
      res.status(404).send(
        jsend(404, {
          message: "Product not found!",
        })
      );
    });
};

The response will be like this:

{
  "name" : "Iphone 12",
  "description" : "Used Iphone for sale",
  "price" : "500",
  "currency" : "USD",
  "_id" : "2c03c6d94312bf24069e38b1",
}

“PATCH” product data by id

Now we will create a PATCH operation.

To do that we will first create a route in /routes/product.config.js:

app.patch('/products/:productId', [
    ProductsController.patchById
]);

Add a controller in products.controller.js:

ProductModel.findOneAndUpdate({ _id: req.params.productId }, req.body)
    .then((product) => {
      if (!product) {
        return res.status(404).send(
          jsend(404, {
            message: "Product not found!",
          })
        );
      }

      res.status(200).send(
        jsend(200, {
          product,
        })
      );
    })
    .catch((err) => {
      res.status(404).send(
        jsend(404, {
          message: "Product not found!",
        })
      );
    });

If we pass JSON data using PATCH to /products/2c03c6d94312bf24069e38b1  with changed data like:

{
  "name" : "Iphone 12 pro",
  "description" : "Used Iphone 12 Pro for sale",
  "price" : "450",
  "currency" : "USD"
}

We will get changed data like:

{
  "name" : "Iphone 12 pro",
  "description" : "Used Iphone 12 Pro for sale",
  "price" : "450",
  "currency" : "USD"
  "_id" : "2c03c6d94312bf24069e38b1"
}

“DELETE” product by id

And the last part to be implemented is the DELETE at /products/2c03c6d94312bf24069e38b1.

First, we create a route in /routes/product.config.js:

app.delete('/products/:productId', [
    ProductsController.removeById
]);

After that add a new controller in products.controller.js:

exports.delete = (req, res) => {
ProductModel.findOneAndDelete(
  { _id: req.params.productId },
  (err, product) => {
    if (err) {
      return res.status(500).send(
        jsend(500, {
          message: "An error occurred and the Product could not be removed!",
        })
      );
    }

    if (!product) {
      return res.status(404).send(
        jsend(404, {
          message: "Product not found!",
        })
      );
    }

    res.status(200).send(
      jsend(200, {
        product._id,
      })
    );
  }
);
};

So if we send DELETE to /products/2c03c6d94312bf24069e38b1 with Postman it will delete that product.

Conclusion

In this tutorial, we have created a basic REST api for CRUD operations under the Product scheme.

You can use this knowledge to create your new api endpoint and create amazing applications in the future.
Till then check out our other tech blogs and stay tuned folks! 🙂

Srdjan Nezic

Senior Full-Stack Web Developer


Srdjan Nezic

Senior Full-Stack Web Developer

I am a seasoned Senior Full Stack Web Developer boasting a rich 12-year tenure in the field of web development. My fervor for crafting digital solutions propels me to seamlessly integrate both frontend and backend proficiencies in conceiving pioneering websites and applications. During my leisure hours, I am dedicated to disseminating knowledge through the medium of blogging.

Share this post

Share this link via

Or copy link