0% found this document useful (0 votes)
6 views

MongoDB Rest API

The document outlines the process of building a REST API using Express, Node, and MongoDB, emphasizing the importance of JavaScript in web development. It explains the four main operations of a REST API (GET, POST, PUT, DELETE) and provides step-by-step instructions for setting up the project, including installing necessary packages and creating the API endpoints. Additionally, it includes sample code for the main application and user schema to demonstrate the implementation of the REST API functionalities.

Uploaded by

heheboiburnerid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

MongoDB Rest API

The document outlines the process of building a REST API using Express, Node, and MongoDB, emphasizing the importance of JavaScript in web development. It explains the four main operations of a REST API (GET, POST, PUT, DELETE) and provides step-by-step instructions for setting up the project, including installing necessary packages and creating the API endpoints. Additionally, it includes sample code for the main application and user schema to demonstrate the implementation of the REST API functionalities.

Uploaded by

heheboiburnerid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

PARSHVANATH CHARITABLE TRUST'S

A. P. SHAH INSTITUTE OF TECHNOLOGY


(All Branches NBA Accredited)
Department of Information Technology

Building a REST API with Express, Node, and MongoDB

JavaScript is considered the top web development language today, running in millions of
applications and websites. One of the building blocks for the JavaScript stack, on many of its
variations, is REST API-based communication between the front-end and back-end tiers.A
popular way of implementing the REST API approach uses Express JS as the back-end web
server and MongoDB as the document store. This concept easily maps MongoDB’s document
model to the REST API payloads which are JSON by nature.

API mean Application Programming Interface, which is a set of clearly defined methods of
communication between the frontend and the database.
REST which stands for Representational State Transfer, is an architectural style for providing
standards between computer systems on the web, making it easier for systems to communicate
with each other.
REST APIs mostly use JSON as the preferred choice for transferring data as they are easy to
understand and is readable.

In this experiment, we will be using Node, Express and MongoDB to create a REST API that
would support the four operations — GET, POST, PUT and DELETE.
So, let’s first discuss these four operations and try to understand what they actually mean in the
context of API development.
GET — GET means to read the data. The function of this operation is to retrieve the data from
the database and present it to the user.
POST — POST, as the name suggests, is used to post/add new data to the database. It allows
users to add new data to the database.
PUT — PUT means to update the data already present in the database.
DELETE — It is used to delete any existing data from the database.
So, our REST API will perform all these operations. We will use the Express package to make
our work easier. We will use MongoDB as the NoSQL database to store all our data. So, we
will do it step by step. First, we would build the API endpoints and then we would connect to

Department of Information Technology | APSIT


PARSHVANATH CHARITABLE TRUST'S

A. P. SHAH INSTITUTE OF TECHNOLOGY


(All Branches NBA Accredited)
the database to perform actual operations. We would use Postman software for API testing.
Setting up the Project
First of all, we need to download Node on our system. Then we can start creating our project.
So, first of all, we need to create a folder in our system where we would love to build our
project. I kept the name of the folder as rest-API.
Then we need to move into the rest-API folder we created just now. Now to start a new project,
we would run the following command within the folder:-
npm init
After completion, we will see a package.json file in the folder. It contains all the data we just
gave to create this file. You can see the entry point is the app3.js file.
After creating the package.json file, we need to download Express on our machine. To install
Express, we use following command
npm install express --save
This will download and save express in our system and also will add express as a dependency
in our package.json file. We will also download a development dependency named nodemon
which will allow us to develop faster. It will help us to avoid restarting the server each time we
make a change and will automatically refresh, which would save us a lot of time.So, to install
nodemon, we would do:
npm install --save-dev nodemon
Now, we need to download MongoDB in our system and then create the cluster and connect it
with your local computer.
Next, we need to download mongoose to interact with the MongoDB database from our express
application.
To install mongoose, we use following command
npm install mongoose --save
So, let’s start building our REST API. First of all, we need to create a file named app.js as we
can see it is the entry point to our application. So, then we would set up a GET function to test
it out using the browser. We pass a message as the response when we have a GET request to
localhost:3000/API. You can choose the port number as per your choice. We will console.log
a message to check if it is working properly. Next, below the set up of our express app, we
would like to connect to MongoDB. We would then add Express parser to parse the data sent
or received from the database.
To test out the operations, we would use a software called Postman. It is helps to test out APIs
Department of Information Technology | APSIT
PARSHVANATH CHARITABLE TRUST'S

A. P. SHAH INSTITUTE OF TECHNOLOGY


(All Branches NBA Accredited)
really fast. Download the Postman desktop agent or install its Chrome extension to start using
Postman. Here, we can choose the type of operation and the target URL for sending requests.
For POST requests, we need to send some JSON data while sending request which we can be
done by adding the JSON in the Body section. You need to select Raw data type and then chose
JSON as the format. Next, using mongoose we would create schema user.js file within the
folder. A Schema tells how the data is to be structured.
Below is the program for building a REST API with Express, Node, and MongoDB.

Program

This is program for app3.js

const express = require('express');


const app = express();
const mongoose = require('mongoose');
app.use(express.json());
//const User = require("./model/user");
const User = require("./user");

app.listen(3000,() => {(console.log("listening to 3000"));});

app.get("/", (req,res) =>{


res.send("First Request!!! welcome");});

app.get("/users", (req,res) =>{


let users =["Navya","Shital","Shweta","Sonal"];
res.send({"users":users,});});

//retrieve from DB
app.get("/get_users", async(req,res) =>{
try {

const user = await User.find();


// res.json(user);
res.send(user);
} catch (error) {
res.send("Error "+error);
}

});

mongoose.connect("mongodb+srv://admin:admin123@cluster0.d1h2r.mongodb.net/testdb?re
Department of Information Technology | APSIT
PARSHVANATH CHARITABLE TRUST'S

A. P. SHAH INSTITUTE OF TECHNOLOGY


(All Branches NBA Accredited)
tryWrites=true&w=majority",
{useNewUrlParser: true,
useUnifiedTopology: true,
}).then(()=> {
console.log("connection successful");
}).catch((err) => console.log("no connection"+err.message));

app.post("/create_user", async(req,res) =>{


try {
// console.log(req.body.name);
const myuser = new User(req.body);
myuser.save();
res.send(myuser)
} catch (error) {
res.send({ message: error});
}
}
);

This is code for user.js

const mongoose =require("mongoose");

const User = new mongoose.Schema({


name:{
type:String,
required: true,
},
age:{
type:Number,
required: true,
},
});

module.exports = mongoose.model("user", User);

Department of Information Technology | APSIT

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy