Open In App

How to build Node.js Blog API ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to create a blog API using Node.js. A Blog API is an API by which users can fetch blogs, write blogs to the server, delete blogs, and even filter blogs with various parameters.

Functionalities:

  • Fetch Blogs
  • Create Blogs
  • Delete Blogs
  • Filter Blogs

Approach: In this project, we will use some modules such as express for writing code, body-parser for fetching user input values, and mongoose to connect with the MongoDB database. Then we will create different routes for different purposes such as the get route for fetching blogs, the post route for posting blogs, delete route for deleting blogs.

Implementation: Below is the step-by-step implementation of the above approach.

Step 1: Project Setup

Initializes NPM: Create and Locate your project folder into the terminal & type the command

npm init -y

It initializes our node application & makes a package.json file.

Install Dependencies: Locate your root project directory into the terminal and type the command

npm install express

To install Express as dependencies inside your project

Create Server File: Create an ‘app.js’ file, inside this file require an express Module, and create a constant ‘app’ for creating an instance of the express module.

const express = require('express')

const app = express()

Fetching data to app.js: To receive input values, we have to use a node package named body-parser.

Install body-parser:

npm install body-parser

Require body-parser module:

const bodyParser = require('body-parser')

And then:

app.use( bodyParser.json() );      
app.use(bodyParser.urlencoded({    
    extended: true
}));

Then we can handle input data using the request object.

Connecting to database: For connecting the MongoDB database, we have to use a module named mongoose.

Install Mongoose:

npm i mongoose

Connect it with the local MongoDB database:

mongoose.connect("mongodb://localhost:27017/blogApi", {
   useNewUrlParser: true,
   useUnifiedTopology: true
});

Create a schema for storing blogs and then create a model Blog using that schema:

const blogSchema = {
   title: String,
   content: String,
}

const Blog = mongoose.model("Blog", blogSchema);

Step 2: Fetch Blogs: Now let’s set up a get route for fetching all blogs, inside this route, we will use the find method and pass nothing as an argument, this will get all the blogs and then we will send it to the response or send the error if found.

app.get('/blogs', (req, res) => {
   Blog.find({}, (err, blog) => {
       if (err) {
           res.send(err);
       } else {
           res.send(blog);
       }
   })
})

Step 3: Filter Blogs: Modify the route giving an option to fetch the blogs using title, inside this route, we will use the find method and pass the requested title as an argument, this will get the requested blog and then we will send it to the response or send the error if found.

app.get('/blogs/:blogTitle', (req, res) => {
   Blog.find({ title: req.params.blogTitle }, (err, blog) => {
       if (err) {
           res.send(err);
       } else {
           res.send(blog);
       }
   })
})

Step 4: Create Blogs: Now, let’s set up a post route, in which we will fetch the user input values such as title and content using bodyparser then create a new blog and then save it then we will send a successful message or send the error if found.

app.post('/blogs', (req, res) => {
   const title = req.body.title
   const content = req.body.content
   const blog = new Blog({
       title: title,
       content: content
   })
   blog.save(err => {
       if(err) {  res.send(err); }
       else { res.send('blog added!'); }
   });
})

Step 5: Delete Blogs: Now, let’s set up a delete route,  in which we will fetch the user input value such as title using bodyparser then delete the blog having the same title using the delete method with the title as arguments then we will send a successful message or send the error if found.

app.delete('/blogs', (req, res) => {
   const title = req.body.title
   Blog.deleteOne({ title: title }, (err, blog) => {
       if (err) {
           res.send(err);
       } else {
           res.send("blog deleted!");
       }
   })
})

Step 6: Set up a port to run our server: We will do it by using the express, listen method.

app.listen(3000, () => {
   console.log("listening on http://localhost:3000");
})

Complete Code:

Javascript




const express = require('express')
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
 
const app = express()
 
app.use(bodyParser.urlencoded({
    extended: true
}))
 
mongoose.connect("mongodb://localhost:27017/blogApi", {
    useNewUrlParser: true,
    useUnifiedTopology: true
});
 
const blogSchema = {
    title: String,
    content: String,
}
 
const Blog = mongoose.model("Blog", blogSchema);
 
app.get('/blogs', (req, res) => {
    Blog.find({}, (err, blog) => {
        if (err) {
            res.send(err);
        } else {
            res.send(blog);
        }
    })
})
 
app.get('/blogs/:blogTitle', (req, res) => {
    Blog.find({ title: req.params.blogTitle },
    (err, blog) => {
        if (err) {
            res.send(err);
        } else {
            res.send(blog);
        }
    })
})
 
app.post('/blogs', (req, res) => {
    const title = req.body.title
    const content = req.body.content
 
    const blog = new Blog({
        title: title,
        content: content
    })
 
    blog.save(err => {
        if(err) {  res.send(err); }
        else { res.send('blog added!'); }
    });
})
 
app.delete('/blogs', (req, res) => {
    const title = req.body.title
 
    Blog.deleteOne({ title: title }, (err, blog) => {
        if (err) {
            res.send(err);
        } else {
            res.send("blog deleted!");
        }
    })
})
 
app.listen(3000, () => {
    console.log("listening on http://localhost:3000");
})


Step to run the application: Inside the terminal type the  following command

node app.js

Output:

 



Last Updated : 06 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads