DEV Community

Cover image for Creating RESTful APIs with Node and MongoDB
Angha Ramdohokar
Angha Ramdohokar

Posted on

Creating RESTful APIs with Node and MongoDB

During my career as a software developer, I have written RESTful APIs in different languages and used different frameworks for it like VB.net, C#, Java, ASP.NET etc. But recently I got an opportunity to create RESTful APIs using Node js.

Node.js is a server-side platform built on Google Chrome's JavaScript Engine (V8 Engine). Node.js provides a backend web application framework called as Express. It is designed for building web applications and APIs. MongoDB is an open-source document-oriented database.

We’ll be building a RESTful CRUD (Create, Retrieve, Update, Delete) API with Node.js, Express and MongoDB. We’ll use Mongoose for interacting with the MongoDB instance.

Prerequisites

  1. Install Node.js and MongoDB on your machine if you have not done already and use any development environment like Visual Studio Code

Creating application

  1. Open new terminal and create new folder for the application.
PS C:\> mkdir node-blog-app
Enter fullscreen mode Exit fullscreen mode

2.Initialize application with package.json file

At root of the folder, type npm init to initialize your app with a package.json file.

PS C:\> cd node-blog-app      
PS C:\node-blog-app> npm init
Enter fullscreen mode Exit fullscreen mode
package name: (blog-app) node-blog-app
version: (1.0.0)
description: Creates blogs easily and quickly.
entry point: (index.js) server.js
test command:
git repository:
keywords: Express,RestAPI,MongoDB,Mongoose,Blogs
author: dev.to
license: (ISC)
Enter fullscreen mode Exit fullscreen mode

Here we have defined entry point as server.js file so we will create it further down.

3.Install application dependencies

We will need express, mongoose. Let’s install them by typing the following command -

PS C:\node-blog-app> npm install express mongoose --save  
Enter fullscreen mode Exit fullscreen mode

--save will save these dependencies in package.json file.

4.Setting up the web server
Now we will create the main entry point of our application named server.js in the root folder of the application with the following contents-

const express = require('express');

// create express app
const app = express();

// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }))

// parse requests of content-type - application/json
app.use(express.json())

// define a simple route
app.get('/', (req, res) => {
    res.json({"message": "Welcome to E-Blog. Creates blogs easily and quickly."});
});

// listen for requests
app.listen(3000, () => {
    console.log("Server is listening on port 3000");
});
Enter fullscreen mode Exit fullscreen mode

First, we import express then we create an express app, and add two parser middlewares using express’s app.use() method.

If you are using Express >= 4.16.0, body parser has been re-added under the methods express.json() and express.urlencoded().

Then, We define a simple GET route which returns a welcome message to the clients.
Finally, We listen on port 3000 for incoming connections.

Let’s now run the server and go to http://localhost:3000 to access the route we just defined.

PS C:\node-blog-app> node server.js
Enter fullscreen mode Exit fullscreen mode

Alt Text

5.Database configuration and connection
Create new file named as database.config.js inside app/config folder with the following contents -

module.exports = {
    url: 'mongodb://localhost:27017/blogs'
}
Enter fullscreen mode Exit fullscreen mode

Now we will import the above database configuration in server.js and connect to the database using mongoose.

Add the following code to the server.js.

// Configuring the database
const dbConfig = require('./config/database.config.js');
const mongoose = require('mongoose');

mongoose.Promise = global.Promise;

// Connecting to the database
mongoose.connect(dbConfig.url, {
    useNewUrlParser: true
}).then(() => {
    console.log("Successfully connected to the database");    
}).catch(err => {
    console.log('Could not connect to the database. Exiting now...', err);
    process.exit();
});
Enter fullscreen mode Exit fullscreen mode

Please run the server.js and make sure that you’re able to connect to the database -

PS C:\node-blog-app> node server.js
Server is listening on port 3000
Successfully connected to the database
Enter fullscreen mode Exit fullscreen mode

6.Defining the Blog model in Mongoose
Create a file called blog.model.js inside app/models folder with the following contents -

const mongoose = require('mongoose');

const BlogSchema = mongoose.Schema({
    title: String,
    content: String
}, {
    timestamps: true
});

module.exports = mongoose.model('Blog', BlogSchema);
Enter fullscreen mode Exit fullscreen mode

7.Defining Routes using Express
Create a new file called blog.routes.js inside app/routes folder with the following contents -

module.exports = (app) => {
    const blogs = require('../controllers/blog.controller.js');

    // Create a new Blog
    app.post('/blogs', blog.create);

    // Retrieve all Blogs
    app.get('/blogs', blog.findAll);

    // Update a Blog with blogId
    app.put('/blogs/:blogId', blog.update);

    // Delete a Blog with blogId
    app.delete('/blogs/:blogId', blog.delete);
}
Enter fullscreen mode Exit fullscreen mode

8.Writing Controller functions
Create a new file called blog.controller.js inside app/controllers folder.

Creating a new Blog-

// Create and Save a new Blog
exports.create = (req, res) => {

    // Create a Blog
    const blog = new Blog({
        title: req.body.title, 
        content: req.body.content
    });

    // Save Blog in the database
    blog.save()
    .then(data => {
        res.send(data);
    }).catch(err => {
        res.status(500).send({
            message: err.message || "Some error occurred while creating the Blog."
        });
    });
};
Enter fullscreen mode Exit fullscreen mode

Retrieving all Blogs -

// Retrieve and return all blogs from the database.
exports.findAll = (req, res) => {
    Blog.find()
    .then(blogs => {
        res.send(blogs);
    }).catch(err => {
        res.status(500).send({
            message: err.message || "Some error occurred while retrieving blogs."
        });
    });
};
Enter fullscreen mode Exit fullscreen mode

Updating a Blog -

// Update a blog identified by the blogId in the request
exports.update = (req, res) => {

    // Find blog and update it with the request body
    Blog.findByIdAndUpdate(req.params.blogId, {
        title: req.body.title,
        content: req.body.content
    }, {new: true})
    .then(blog => {
        if(!blog) {
            return res.status(404).send({
                message: "Blog not found with id " + req.params.blogId
            });
        }
        res.send(blog);
    }).catch(err => {
        if(err.kind === 'ObjectId') {
            return res.status(404).send({
                message: "Blog not found with id " + req.params.blogId
            });                
        }
        return res.status(500).send({
            message: "Error updating blog with id " + req.params.blogId
        });
    });
};
Enter fullscreen mode Exit fullscreen mode

The {new: true} option in the findByIdAndUpdate() method is used to return the modified document to the then() function instead of the original.

Deleting a Blog-

// Delete a blog with the specified blogId in the request
exports.delete = (req, res) => {
    Blog.findByIdAndRemove(req.params.blogId)
    .then(blog => {
        if(!blog) {
            return res.status(404).send({
                message: "Blog not found with id " + req.params.blogId
            });
        }
        res.send({message: "Blog deleted successfully!"});
    }).catch(err => {
        if(err.kind === 'ObjectId' || err.name === 'NotFound') {
            return res.status(404).send({
                message: "Blog not found with id " + req.params.blogId
            });                
        }
        return res.status(500).send({
            message: "Could not delete blog with id " + req.params.blogId
        });
    });
};
Enter fullscreen mode Exit fullscreen mode

Check out Mongoose API documentation.

Testing of Blogs API-
Check out this in POSTMAN to test Blogs APIs.

Conclusion
In this blog, We learned how to build REST APIs in Node.js using express framework and mongodb.
Please ask any questions that you might have in the comment section below.

Thanks for reading.

Oldest comments (4)

Collapse
 
praneetrane profile image
Praneet Rane

Very nice and detailed, Thanks for sharing!

Collapse
 
paresh4734 profile image
Paresh Awashank

Very useful for beginners!!!

Collapse
 
ravi8080 profile image
Ravindra Shivdas

Thank you for sharing in-depth details !!

Collapse
 
meghaghotkar profile image
Megha Ghotkar

This is helpful. Thanks for sharing !