Create a REST API in Express and MongoDB
Hey guys! Today I thought to give you a very useful tutorial based on Node JS! I think you may have already heard the word API or REST API.. A REST API is an application program interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. This is the basis for any MEAN application! As an example, imagine that you are going to build a Blog using MEAN stack technology. So, you need a back-end + front-end to accomplish this task. Back-end means the functionalities and the front-end means the user interfaces. This API is related to your back-end.
For this we need these things in our machine :
- Node JS (check using node -v and npm -v. If it is not installed, install now!)
- MongoDB
- Postman (API testing tool)
Step 1 - Initiate the peoject
Make a project folder and open it in a text editor like Sublime or VS Code. We have to initiate a Node JS project. Open cmd and go into the folder you created. Type npm init and wait. It will ask you for some details. Step by step, you have to hit enter to record them in the project. If you do not want to change the default values, just hit enter and go the next step. Give the required and finally confirm it.
package name: project name ( keep as default )
version: version of project ( keep as default )
description: short intro to the project
entry point: main file that serves after project creation
author: creator's name
test command, git repository, keywords, license - keep as default
This will create a new file called package.json which contains the dependencies for your project.
Step 2 - Implement the server
Since I entered the entry point as app.js, I must create my server file using this name. So, create a file with name you provided for the entry point.We are not going to use pure Node JS. We can use Express JS framework to make easier implementations with less coding. It is the mostly used Node Js framework. So we have to install express js into our project. Open cmd and go into the project. Hit the below command.
npm install express --save
Then modify the app.js file like this.app.js - version 1
// Load express module
const express = require('express');
// Initialize app
const app = express();
// Initialize port
const port = 3000;
// Initialize paths
const path = require('path');
// Initialize public directory
app.use(express.static(path.join(__dirname, 'public')));
// Route for home
app.get('/', function(req, res){
res.send('Hello from Server');
})
// Start server with port 3000
app.listen(port, function(){
console.log('Server is starting at ' + port);
})
Open the web browser and type localhost:3000 in the address bar. You will see "Hello from server". Now our server is ready!
Step 3 - Connect to MongoDB
For more details read this article.
Now we are going to make a connection with local MongoDB. Using Mongo Shell or Compass, create a new database called api. Crate a collection called posts. (since I'm going to handle with some blog posts)
Now we have to modify the code to connect to the database. I'm going to use Mongoose package for this. Install it from npm. Open cmd and go into the project. Hit the below command.
npm install mongoose --save
app.js - version 2
// Load express module
const express = require('express');
// Initialize app
const app = express();
// Initialize port
const port = 3000;
// Initialize paths
const path = require('path');
// Initialize public directory
app.use(express.static(path.join(__dirname, 'public')));
// Mongoose connection
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/api');
const db = mongoose.connection;
// Check for DB connection
db.once('open', function(){
console.log("Connected to MongoDB successfully!");
});
db.on('error', function(){
console.log(err);
});
// Route for home
app.get('/', function(req, res){
res.send('Hello from Server');
})
// Start server with port 3000
app.listen(port, function(){
console.log('Server is starting at ' + port);
})
As soon as we make changes in the server file, we have to stop it and start it again to track the changes. This is annoying. So install nodemon package to avoid this problem. Once we started server through nodemon, it will track all the changes and auto reload the server.
npm install -g nodemon --save
After installation of nodemon, we can start the server by typing just nodemon. No need to type node app.js.
Structure contains key pair values to be used with MongoDB.
models/post.js
npm install -g nodemon --save
After installation of nodemon, we can start the server by typing just nodemon. No need to type node app.js.
Step 4 - Create a Schema for the database
We have to define a Schema for our application data. Giving all the fields we expect to include in a post, we can create this. Create a new folder called models within the project folder. Then inside it, create a new schema called post.js. Ipen it and enter this code.Structure contains key pair values to be used with MongoDB.
models/post.js
Step 5 - Implement a router for navigation
We have to make routes for our project. All the routes should be implemented separately without including them in the main server file. First we have to decide how to organize the routes related to the URL format. I would like to see my all routes with a prefix like "api". So I have to tell about it to the server. Open app.js and include this.
const posts = require('./routes/router');
app.use('/api', posts);
Now my routes will be => localhost:3000/api/posts, localhost:3000/api/post/1......Next part is to create a routes folder. Then create a file called router.js. All the key functionalities for CRUD operations are included in this code.
routes/router.js
Step 6 - Add Body Parser and Cors
Now our functions are ready to be used! But there's another important section.. In our API, there are functions that send POST requests. We have to take inputs from the body of the request. So we should install Body Parser middle-ware. Body-parser is a piece of express middleware that reads a form's input and stores it as a JavaScript object accessible through req.body. Open up a terminal/cmd and go into the project. Then type the below command.npm install body-parser --save
Now include in the project. Open app.js and add this code.
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
Another problem is there. When you try to send request from API now, it will throw an error saying Access-Header problem! Such kind of security issues must be solved. Install CORS module using this command.
npm install cors --save
Then use it in app.js file in this way. This will look after all header access problems in the routes in our project.
const cors = require('cors');
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
})
Final version of app.js is this one!
Now our API is ready guys!
Add some documents to our collection - posts in the database. Provide the details according to the prepared Schema.
Step 7 - Test the API with Postman
Now open a new tab using plus mark in the UI. Check the router.js file for route URLs.
1. Check the route getting all the post - GET request
Choose the option as GET.. not POST..URL => localhost:3000/api/postsThen click on SEND. You will see the result on the below window area.
2. Check the route getting single post - GET request
Choose the option as GET.. URL => localhost:3000/api/posts/idSelect an id from the documents..I selected first post ID..Then click on SEND.
You will see the result..
3. Check the route adding a post - POST request
Choose the option as POST..Here we have to give the post details. So after selecting POST, you will get some options Authorization, Headers, Body.... Select Body from it. Then you will get set of check-boxes. Select row checkbox from them. At last, you will have to select type of data. Select json from that dropdown.
URL => localhost:3000/api/posts/addThen click on SEND.
4. Check the route editing a post - GET request
Choose the option as GET.. URL => localhost:3000/api/posts/edit/idSelect an id from the documents..I selected first post ID..Then click on SEND.
You will see the result..
5. Check the route updating a post - POST request
Here we have to give the new post details. Change one or two details. I changed the description. So after selecting POST, you will get some options Authorization, Headers, Body.... Select Body from it. Then you will get set of check-boxes. Select row checkbox from them. At last, you will have to select type of data. Select json from that dropdown.
URL => localhost:3000/api/posts/update/idThen click on SEND. The post has been updated.
Check the post again to confirm the update. GET request - localhost:3000/api/posts/id
6. Check the route deleting a post - DELETE request
Choose the option as DELETE.. Then pass an ID of a post. I passed 3rd post's ID.URL => localhost:3000/api/posts/id
Then click on SEND. You will see the result..
OK guys! We have finished testing our API...! It is correctly functioning.. So, now I have completed the article with all the details needed for an API creation.
Expess JS and MongoDB always works well together. So this is the easiest and clean way to create an API for our projects. Try this and give me your feedback!
If you have any question, please drop a comment..
Good Bye guys!
6 Comments
ReplyDeleteNice article,keep on sharing. Check it once through.
Full Stack online Training
Full Stack Training
Full Stack Developer Online Training
Full Stack Training in Hyderabad
Full Stack Training in Ameerpet
Full Stack Training Institute
Thank you Vishnu!
DeleteThank you for excellent article
ReplyDeleteUI Development Training
UI Development Training in Hyderabad
UI Development Online Training
Thank you very much Kavya!
DeleteThanks for sharing Awesome blog with us.
ReplyDeleteNode JS Online training
Node JS training in Hyderabad
Discover the top Manufacturing erp software for automotive inventory management, and resource planning. Improve operational efficiency, reduce costs, and boost productivity with the best ERP systems tailored to meet the unique needs of manufacturing businesses. Compare features and benefits to find the perfect fit for your organization's success.
ReplyDelete