20. Diving into API's

Faraz AlamFaraz Alam
6 min read
  • in the context of mongoDB and express, an API(application programming interface) refer to set of end point that allow external application to interact with MongoDB database through HTTP request.

in part 19 we have seen how to create a post api to save data to database which look like this

POST API

const express = require("express");
const app = express();
const port = 3000;
const connectDB = require("./config/database"); //getting DB connection
const User = require("./models/user"); //getting User model
app.post("/user", async (req, res) => {
1.  const user = new User({
    firstName: "faraz",
    lastName: "alam",
    email: "test@123.com",
    password: "test@123",
    City: "Pune",
 2. });
  try {
    await user.save();
    res.send("user addedd sucessfully");
  } catch (err) {
    res.status(400).send("error saving the data:- " + err.message);
  }
});

connectDB()
  .then(() => {
    console.log("connected to DB");
    app.listen(port, () => {
      console.log(`Server is running on port ${port}`);
    });
  })
  .catch((err) => {
    console.error("Not connected to DB");
  });

but here we have entered static data to create a new Instance of User model in line 1-2 , but in real world this data is dynamic.

  • Now lets take data from postman dynamically and push it inside post API and then save this data to database

  • this is data which is entered in postman in form of JSON object, remember it is JSON object not JS object there is difference between both term JS object have key-value pairs with key can be of any data type like string, number etc. but in JSON object these are double-inverted commas containing property-value pairs, when we try do console.log(req.body), “req“ is request that is send by postman and received in API, with data sent in body of postman is part of “req“. we get undefined as our server is not able to read JSON data hence we need a middleware which convert our JSON data into JS object which can we consoled without showing undefined using (express.json()) as middleware.

const express = require("express");
const app = express();
const port = 3000;
const connectDB = require("./config/database"); //getting DB connection
const User = require("./models/user"); //getting User model
app.use(express.json());//act as middleware for converting JSON data from req.body to JS object for all 
http request(get, post, patch, delete)
app.post("/user", async (req, res) => {
  console.log(req.body);
  try {
    res.send("user addedd sucessfully");
  } catch (err) {
    res.status(400).send("error saving the data:- " + err.message);
  }
});
connectDB()
  .then(() => {
    console.log("connected to DB");
    app.listen(port, () => {
      console.log(`Server is running on port ${port}`);
    });
  })
  .catch((err) => {
    console.error("Not connected to DB");
  });

  • now we can simply create new instance from our User model using data coming from req.body which further can save data to database

      const express = require("express");
      const app = express();
      const port = 3000;
      const connectDB = require("./config/database"); //getting DB connection
      const User = require("./models/user"); //getting User model
      app.use(express.json()); //act as middleware for converting JSON data from req.body to JS object for all http request(get, post, patch, delete)
      app.post("/user", async (req, res) => {
        const user = new User(req.body);//creating a instance of User model from data coming from request body
        try {
          await user.save();
          res.send("user addedd sucessfully");
        } catch (err) {
          res.status(400).send("error saving the data:- " + err.message);
        }
      });
      connectDB()
        .then(() => {
          console.log("connected to DB");
          app.listen(port, () => {
            console.log(`Server is running on port ${port}`);
          });
        })
        .catch((err) => {
          console.error("Not connected to DB");
        });
    

Feed API

  • feed api is mostly used to get all documents or data from database

      const express = require("express");
      const app = express();
      const port = 3000;
      const connectDB = require("./config/database"); //getting DB connection
      const User = require("./models/user"); //getting User model
      app.use(express.json()); //act as middleware for converting JSON data from req.body to JS object for all http request(get, post, patch, delete)
      app.get("/feed", async (req, res) => {
        try {
          const user = await User.find({});
          if (user.length === 0) {
            res.status(404).send("user list empty");
          } else {
            res.send(user);
          }
        } catch (err) {
          res.status(400).send("error saving the data:- " + err.message);
        }
      });
      connectDB()
        .then(() => {
          console.log("connected to DB");
          app.listen(port, () => {
            console.log(`Server is running on port ${port}`);
          });
        })
        .catch((err) => {
          console.error("Not connected to DB");
        });
    

GET API

getting data using find() method with filters

const express = require("express");
const app = express();
const connectDB = require("./config/database"); //getting DB connection
const port = 3000;
const User = require("./models/user"); //getting User model
app.use(express.json());
app.get("/user", async (req, res) => {
  const userEmail = req.body.emailId;
  try {
    const user = await User.find({ emailId: userEmail });
    if (user.length === 0) {
      res.status(404).send("user list empty");
    } else {
      res.send(user);
    }
  } catch (err) {
    res.status(400).send("error saving the data:- " + err.message);
  }
});
connectDB()
  .then(() => {
    console.log("connected to DB");
    app.listen(port, () => {
      console.log(`Server is running on port ${port}`);
    });
  })
  .catch((err) => {
    console.error("Not connected to DB");
  });

DELETE API

  • lets see how to delete data using filter combine with method findByIdAndDelete()

      const express = require("express");
      const app = express();
      const connectDB = require("./config/database"); //getting DB connection
      const port = 3000;
      const User = require("./models/user"); //getting User model
      app.use(express.json());
      app.delete("/user", async (req, res) => {
        const userID = req.body.userId;
        try {
          const user = await User.findByIdAndDelete({ _id: userID });
          res.send("deleted success");
        } catch (err) {
          res.status(400).send("Error;- " + err.message);
        }
      });
      connectDB()
        .then(() => {
          console.log("connected to DB");
          app.listen(port, () => {
            console.log(`Server is running on port ${port}`);
          });
        })
        .catch((err) => {
          console.error("Not connected to DB");
        });
    

    You can find important methods to manipulate the data from mongoDB here MongoDB methods

UPDATE / PATCH API

  • it is used to update the existing field data of the document of database, mostly we use method like findByIdAndUpdate()

  • mostly in these API we are not able to validate data to provide data transfer in safe manner, hence we need data sanitization which we can learn later.

      const express = require("express");
      const app = express();
      const connectDB = require("./config/database"); //getting DB connection
      const port = 3000;
      const User = require("./models/user"); //getting User model
      app.use(express.json());
      app.patch("/user", async (req, res) => {
        const userId = req.body.userId;
        const data = req.body;
        try {
          const user = await User.findByIdAndUpdate({ _id: userId }, data, {
            returnDocument: "before", //this returnDocument is added to know the data before or after updation
          });
          console.log(user);
          res.send("updated successfully");
        } catch (err) {
          res.status(400).send("Error:- " + err.message);
        }
      });
      connectDB()
        .then(() => {
          console.log("connected to DB");
          app.listen(port, () => {
            console.log(`Server is running on port ${port}`);
          });
        })
        .catch((err) => {
          console.error("Not connected to DB");
        });
    

  • if we try to update field which not exist then there will be no effect on code

GET / POST / DELETE / PATCH all together

const express = require("express");
const app = express();
const connectDB = require("./config/database"); //getting DB connection
const port = 3000;
const User = require("./models/user"); //getting User model
app.use(express.json());
app.get("/user", async (req, res) => {
  const userEmail = req.body.emailId;
  try {
    const user = await User.find({ emailId: userEmail });
    if (user.length === 0) {
      res.status(404).send("user list empty");
    } else {
      res.send(user);
    }
  } catch (err) {
    res.status(400).send("error saving the data:- " + err.message);
  }
});
app.delete("/user", async (req, res) => {
  const userID = req.body.userId;
  try {
    const user = await User.findByIdAndDelete({ _id: userID });
    res.send("deleted success");
  } catch (err) {
    res.status(400).send("Error;- " + err.message);
  }
});
app.post("/user", async (req, res) => {
  const user = new User(req.body);
  try {
    await user.save();
    res.send("data saved success");
  } catch (err) {
    res.status(404).send("error:- " + err.message);
  }
});
app.patch("/user", async (req, res) => {
  const userId = req.body.userId;
  const data = req.body;
  try {
    const user = await User.findByIdAndUpdate({ _id: userId }, data, {
      returnDocument: "before", //this returnDocument is added to know the data before or after updation
    });
    console.log(user);
    res.send("updated successfully");
  } catch (err) {
    res.status(400).send("Error:- " + err.message);
  }
});
connectDB()
  .then(() => {
    console.log("connected to DB");
    app.listen(port, () => {
      console.log(`Server is running on port ${port}`);
    });
  })
  .catch((err) => {
    console.error("Not connected to DB");
  });
0
Subscribe to my newsletter

Read articles from Faraz Alam directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Faraz Alam
Faraz Alam

Assalamualaikum warahmatullah wabarakatuh( traditional Islamic greeting in Arabic "Assalamu alaikum": "Peace be upon you." "Wa rahmatullahi": "And the mercy of Allah." "Wa barakatuh": "And His blessings.") I’m Faraz Alam, and I’m documenting my journey through the world of software technology. Despite earning a master’s degree in Computer Applications and having access to opportunities provided by my tier-3 college, I struggled to take full advantage of them due to poor management and a less productive environment. This led to joblessness, primarily due to a lack of upskilling. Now, I am dedicated to enhancing my skills and knowledge with the aim of securing a valuable job offer from leading product-based companies, including those in the FAANG group (Facebook, Amazon, Apple, Netflix, Google) and other prominent tech giants. This documentation is not for self-promotion; rather, it is for anyone who is waiting for an opportunity but feels they lack the tools and skills required to overcome challenges. It’s a testament to the effort and responsibility needed to navigate the journey towards success when you take charge of your own path. Date: 31 July 2024, 07:25 AM This page will be updated regularly to reflect new achievements and milestones as I continue to build my career.