Creating RESTful APIs with Node and MongoDB
Tags: node, express, api, elastikteams
Published: 2021-09-26 16:20:20

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](https://nodejs.org/en/download/) and [MongoDB](https://docs.mongodb.com/manual/tutorial/install-mongodb-on-windows/) on your machine if you have not done already and use any development environment like [Visual Studio Code](https://code.visualstudio.com/download)

**Creating application**
1. Open new terminal and create new folder for the application.
```
PS C:\> mkdir node-blog-app
```

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
```

```
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)
```
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  
```
***--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");
});
```
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
```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/geqmf8q2lrqwcchgc47f.png)

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'
}
```
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();
});
```
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
```
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);
```

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);
}
```
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."
        });
    });
};
```
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."
        });
    });
};
```
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
        });
    });
};
```
***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
        });
    });
};
```
Check out [Mongoose API documentation](https://mongoosejs.com/docs/api.html).

**Testing of Blogs API**-
Check out [this](https://www.postman.com/anagharamdohokar/workspace/blogsapi/overview) 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.