Building a Rest API using Node and MongoDB

Building a Rest API using Node and MongoDBCodeuixBlockedUnblockFollowFollowingMay 25In this article, we will be learning what an API is, types of API's available and finally build a custom API that allows us to perform CURD operations for our blog website using NodeJs and MongoDB.

What is an API?API is the acronym for Application Program Interface, which is a piece of software intermediary that allows two applications to talk to each other.

Every application that you use to check the weather or send a message instantly on your mobile device, you're using an API.

How API Works?When an application needs to retrieve data from a remote server, It raises a request to the server via API which intern interacts with a remote server and waits for that server to retrieve the requested data, interprets it, performs the necessary actions and sends back a response to the API.

The API Carrying the response provides the data to the application.

Types of API’s AvailableRest API: Rest is the acronym to Representational State Transfer, which is based on URIs and HTTP protocols, and use JSON for a data format.

Here data is a representation of some object.

We can get content of the object using HTTP GET Method, modify the content of the object using a POST, PUT or DELETE Methods.

SOAP API: Soap is the acronym to Simple Object Access Protocol, which is its own protocol and offers more comprehensive features in the way of security, transactions, and ACID (Atomicity, Consistency, Isolation, Durability) compliance then Rest API.

Getting Started.

Hoping that NodeJS is installed on your system, we’ll start by creating a project folder and name it as node-api, open the project directory in your favorite code editor.

If you don't have any code editor in your local computer, My suggestion would be to use Visual Studio code which is the most preferred editor used amongst the developer community.

Visual Studio Code – Code Editing.

RedefinedVisual Studio Code is a code editor redefined and optimized for building and debugging modern web and cloud…code.

visualstudio.

comNow to initialize the project by running the following command in the terminal by navigating to your project folder.

//intitialize the project$ npm init -yDirectory Structureyou will need to organize your project files in the following order to follow along.

Here routes folder contains a file that lists the routes that are available for the application.

You will be using the MVC model to build the application where Model holds all the code that handles the database functionality, the Controller contains the core logic on how each route needs to be handled and interacts with the models to perform specific tasks and View which are not implemented as you are not going to develop pages to showcase the output using templates.

Building the Server in NodeJSWe will need to use an express framework to speed up our development process as all of the basic blocks for setting the server and creating the routes are already provided by express to use it.

Install Express as a dependency in our project using the following command.

npm install express –saveOnce the installation is complete you can start with implementing the server to handle incoming requests.

const express = require('express');const app = express();app.

get('/', (req, res, next) => { res.

send('running node api');});//serving the application the port 3000app.

listen(3000, console.

log('server started on port 3000'));now running the command node app.

js will start the server and fetch the application to run on port 3000 which outputs “running node api” when you the load the URI http://localhost:3000.

Using MongoDBMongoDB can be used as a database server to store, retrieve, update and delete documents for your application, you may use a free tier cluster provided by the MongoDB to deploy database for the application to use.

MongoDB Download CenterDeploy, operate, and scale a MongoDB database in the cloud with just a few clicks.

Fully elastic and highly available…www.

mongodb.

comUse the above link to register and avail your first free cluster provided by MongoDB.

Once you have created and logged into your account navigate to the security tab.

navigate to the security tabCreate a new user with admin privileges to add/modify the database.

Add a new user with Admin privilegesWhitelist the IP address to make sure the cluster can be connected the IP address your application is running on.

Whitelist the IP address 0.

0.

0.

0 to make the cluster available to connect from any of the IP addresses.

Rename the cluster to your liking and wait for it to get configured it will take from few seconds to minute or so to start running.

Using MongoDB in your applicationLet's start by installing the mongoose package which will help us to manage our MongoDB database.

npm install mongoose –saveConnecting to MongoDB database using connection string in app.

jsyou need to replace the user and password in the connection string with the database username and password you created in the last step.

//app.

jsconst express = require('express');const mongoose = require('mongoose');const app = express();//mongoDB connection stringconst url = mongodb+srv://user:<password>@node-api-8r36a.

mongodb.

net/test?retryWrites=true;app.

get('/', (req, res, next)=>{ res.

send('running node api');});mongoose.

connect(url,{useNewUrlParser: true}) .

then(()=>{ app.

listen(3000); console.

log('database connected!');}) .

catch(err => console.

log(err)); app.

listen(3000);}) .

catch(err => console.

log(err));now if you run the command node app.

js it will output “database connected!” once the connection is established.

Handling Routing externallyRemoving routing from our core application will make application easier to maintain as we can divide different aspects of the application into sub-models that will handle specific tasks rather than a single file handling all the heavy lifting of our application.

Here we will implement routing externally by creating an api_routes.

js file under routes folder and start adding the routers there as shown below.

//api_routes.

js fileconst express = require('express');const router = express.

Router();router.

get('/',(req, res, next) => { res.

send(running node api);})module.

exports = router;modify the app.

js file to use the routes specified in the api_routes.

js file.

//app.

jsconst express = require('express');const mongoose = require('mongoose');const app = express();//mongoDB connection stringconst url = mongodb+srv://user:<password>@node-api-8r36a.

mongodb.

net/test?retryWrites=true;const apiroutes = require('.

/routes/api_route.

js');app.

use('/', apiroutes); //using routes specified externallymongoose.

connect(url,{useNewUrlParser: true}) .

then(()=>{ app.

listen(3000); console.

log('database connected!');}) .

catch(err => console.

log(err));app.

listen(3000);}) .

catch(err => console.

log(err));now we achieved the same result by running the command node app.

js fetching routes from the external file.

Hot reloading using Nodemon.

Let’s install a package called Nodemon that will pick up the changes and restart our server when changes are made to our application.

run the following command to install Nodemon package to our project$ npm install nodemon –save-devHere we can run nodemon app.

js command to start the server.

Further modularizing the applicationIn the recent step, we saw how we can modularize your application by placing the routes in an external file.

here let us see how we can further modularize our application by placing logic that is used to handle the routes in a separate file named post_controller.

js under controllers folder.

//post_controller.

jsexports.

showIndex = (req, res, next) => { res.

send('ruunning node api');}modify your api_route.

js file to get the function to be handled from the controller file.

//api_routes.

js fileconst express = require('express');const postcontroller = require('.

/controller/post_controller');const router = express.

Router();router.

get('/', postcontroller.

showIndex);module.

exports = router;Creating a Post Model in MongoDBHere we’ll see how to create a collection named posts that will be used to store information about the post.

create a file name post_model.

js under the model directory where we will be adding the code necessary to create a post schema for our application.

//post_model.

jsconst mongoose = require('mongoose');const schema = mongoose.

Schema;const postSchema = new Schema({ title:{ type: String, required: true }, description:{ type: String, required: true }, image:{ type: String, required: true }, author:{ type: Date, default: Date.

now }});module.

exports = mongoose.

model('post', postSchema);The above code will create a collection named posts with the following field attributes to store data.

Creating API Routes and Controllershere you will be creating multiple routes to handle requests from the client-server and provide a response by performing a certain operation specified by the controller.

Creating a postcreate an add -post route that handles the post request in the api_routes.

js file.

//api_routes.

jsconst express = require('express');const postcontroller = require('.

/controller/post_controller');const router = express.

Router();router.

post('/add-post', postcontroller.

addPost);module.

export = router;create a function name addPost in a post_controller.

js file that handles the post request made to add-post route and insert the request data into the MongoDB collection.

//post_controller.

jsconst Post = require('.

/model/post_model.

js');//include post schemaexports.

addPost = (req, res, next) => { const post = new Post({ title: req.

body.

title, description: req.

body.

description, image: req.

body.

image }).

then(result => { return result.

save() }).

then(() => { res.

send('post added successfully'); }).

catch(err => { res.

status(400).

send(err); })}Now our API route to create a post is ready to be used before we get started with testing the route we add a middleware in app.

js that parse our request body into JSON and sent the content type to application/json.

//app.

jsapp.

use(express.

json()) //sets content-type to jsonLet's start the server by running nodemon app.

jsWe will use the postman application to test our API Routes, you can download it on your system or install the chrome extension.

Postman | API Development EnvironmentPostman is the only complete API development environment used by more than 6 million developers and 200,000 companies…www.

getpostman.

comOpen postman and enter the API Route to create a post and select post method from the dropdown selection at the left.

Add request headers in the Headers section as shown below.

Finally, let's add the request body containing the post information in JSON format in the body section by checking the raw button and choosing content type JSON (application/json) from the dropdown as shown below.

Now click on the Send button to send the post request, which will send back a JSON response containing the status of the request.

Post Request StatusLet's check our MongoDB collection to verify if the data is been inserted or not by visiting our free cluster provided by MongoDB Atlas.

node-api clusterClick on Collections to view the documents and records.

You could see a test table is been created with the collection named posts and a new document is been added inside the posts collection via the post request made in the previous step.

Read All PostsWe will create a route name posts that will fetch all the posts from the database collection.

Use the HTTP GET method and register the route inside the api_routes.

js file.

//api_routes.

jsrouter.

get('/posts', postcontroller.

showPost);Create a function named showPost inside the post controller that retrieves the posts from the database and sends them back as a response.

//post_controller.

jsexports.

showPost = (req, res, next) => { Post.

find() //fetches all the posts .

then(result => { res.

send(result); }).

catch(err => { res.

status(400).

send(err); })}Use postman to and enter the API Route to view all post records.

Click on the send button to make a get request.

The array JSON string is outputted that contains information of all the posts available in the database.

Retrieve Single PostTo retrieve details of a particular post we should pass the _id field as a parameter to the API route to identify the individual post among all the posts in the database collection.

Create a route named post that is followed by the post id in the api_rotes.

js//api_routes.

jsrouter.

get('/post/:id', postcontroller.

singlePost);Create a function named singlePost inside the post controller that uses the post id parameter passed along with the route to filter the post from the database and send it back as a response.

//post_controller.

jsexports.

singlePost = (req, res, next) => { Post.

findById(req.

params.

id) //filters the posts by Id .

then(result => { res.

send(result); }).

catch(err => { res.

status(400).

send(err); })}Use postman to and enter the API Route followed by the post id by copying the _id field of the post from the database to view the post records.

example route: http://localhost:3000/post/ 5ce9088ea076100fe466294cThe output will showcase the information of a post containing the same _id field as the request parameter.

Updating the PostWe will create a route named post-update which is followed by the id parameter and uses the HTTP PATCH method.

//api_routes.

jsrouter.

patch('/post-update', postcontroller.

updatePost);Create a function named updatePost that gets that post information from the request body and update the post which matches the id field in the request body.

//post_controller.

jsexports.

updatePost = (req, res, next) => { Post.

findById(req.

body.

id) .

then(result => { result.

title = req.

body.

title; result.

description = req.

body.

description; result.

image = req.

body.

image; }).

then(() => { res.

send('post updated successfully'); }).

catch(err => { res.

status(400).

send(err); })}Use postman to and enter the API Route to update the post along with the JSON string containing the updated information in the request body.

output on sending the patch request.

The shows a string stating the post is updated, we can cross-check by visiting posts collection in the database.

updated post document in posts collectionDeleting a Postwe will create a route remove-post which contains post id as a parameter with the HTTP DELETE method.

//api_routes.

jsrouter.

delete('/remove-post/:id', postcontroller.

deletePost);Create a function named deletePost that removes the post from the posts collection which matches the id field provided in the parameter.

//post_controller.

jsexports.

deletePost = (req, res, next) => { Post.

findByIdAndRemove(req.

params.

id) .

then(()=>{ res.

send('post deleted'); }) .

catch(err => res.

status(400).

send(err));};now enter the API route followed by post id in the postman and choose the delete method and sent a request.

We can see the response stating the post is deleted, let's check the database to make sure the post is deleted.

surely, enough the post record is been removed from the posts collection.

Finally, here’s a GitHub repo containing the project files.

SummaryWe gained a little knowledge about what an API is how it plays a major role in our daily lives, build a basic API from scratch using NodeJS and MongoDB that can perform CURD operations on any document set.

Although this is a basic building block to build an API, you can implement your own way of handling the incoming request and personalize the response that needs be sent based on the response status.

Let us know what you felt about this article in the comments below.

.

. More details

Leave a Reply