Skip to content

RESTful API

Updated
17 Sept 2026
2 min read
1 sections
Page 5 of 5
MERN Stack Tutorial

RESTful API

Understanding HTTP status codes

Mozzila Docs

Creating a API connected MongoDB using Express

  1. Importing modules, like express, mongoose, body-parser
javascript
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
  1. Establishing Connection with MongoDB using mongoose
javascript
mongoose
  .connect("mongodb://127.0.0.1:27017/productStore", {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => {
    console.log("Connected to MongoDB successfully");
  })
  .catch((error) => {
    console.log(error);
  });
  1. Creating App reference using Express
javascript
const app = expresss();
  1. Using bodyParser in app to avoid this bug,
javascript
app.use(bodyParser.urlencoded({ extended: false }));
  1. Using express.json() in app to avoid this bug, where only "success" shows up, and it misses "name", "email", " password" from response.json().
javascript
app.use(express.json());
  1. Defining port and host,
javascript
const PORT = 4000;
const HOST = "localhost";
  1. Defining a schema of object and creating a new model
javascript
const productSchema = new mongoose.Schema({
  name: String,
  description: String,
  price: Number,
});

const Product = new mongoose.model("Product", productSchema);
  1. Reading the path to receive data, from POST() to create new product
javascript
app.post("/api/v1/product/new", async (request, response) => {
  const product = await Product.create(request.body);

  response.status(201).json({
    success: true,
    product,
  });
});
  1. Setting up the web server, to listen to host:port
javascript
app.listen(PORT, HOST, () => {
  console.log(`Server is working: http://${HOST}:${PORT}`);
});
  1. Get all products, from /api/v1/products ,
javascript
app.get("/api/v1/products", async (request, response) => {
  const products = await Product.find();

  response.status(200).json({ success: true, products });
});
  1. Modify product detail usiing product id from /api/v1/product/:id
javascript
app.put("/api/v1/product/:id", async (request, response) => {
  let product = await Product.findById(request.params.id);

  product = await Product.findByIdAndUpdate(request.params.id, request.body, {
    new: true,
    useFindAndModify: true,
    runValidators: true,
  });

  response.status(200).json({
    success: true,
    product,
  });
});
  1. Delete product detail usiing product id from /api/v1/product/:id
javascript
app.delete("/api/v1/product/:id", async (request, response) => {
  const product = await Product.findById(request.params.id);

  if (!product) {
    return response.status(500).json({
      success: false,
      message: "Product not found",
    });
  }
  await product.deleteOne();

  response.status(200).json({
    success: true,
    product,
  });
});

Adding Backend Validation using YUP

  1. Installing yup package for validation using npm install yup.
  2. Defining the schema to product, /validation/validateProduct.js,
javascript
const yup = require("yup");

const productSchema = yup.object({
  name: yup.string().required().min(5).max(30),
  description: yup.string().min(10).max(100).required(),
  price: yup.number().required().max(10),
});

module.exports = productSchema;
  1. Creating a middleware that takes schema as parameter, to validate the request with the schema, /middleware/validateMiddleWare.js
javascript
const validation = (schema) => async (request, response, next) => {
  const body = request.body;
  try {
    await schema.validate(body);
    next(); // next() is used to keep moving forward
  } catch (error) {
    return response.status(422).json({ error: error });
  }
};

module.exports = validation;
  1. Importing validation() and schema in app.js, and in Rest API functions call, add validation(schema) as parameter.
javascript
const validation = require("./middleware/validateMiddleware");
const validateSchema = require("./validation/validateProduct");

app.post(
  "/api/v1/product/new",
  validation(validateSchema),
  async (request, response) => {
    const product = await Product.create(request.body);
    response.status(201).json({
      success: true,
      product,
    });
  }
);