Create Server Blog API: Steps or Guides

In this blog post, we are going to be creating an API to handle posting blogs. For this API we will be using nodejs(express). 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 queries.

Functions

  • create user

  • user login in

  • create post

  • fetch posts

  • delete post

  • update post state

  • Search specific posts

Guide

we will use some packages such as express for writing API, body-parser for fetching user input values,joi for validating user inputs, helmet for API security, express-rate-limit for limiting the number of requests to the server and mongoose to connect with the MongoDB database. route and controllers will be created for different purposes such as the post route for creating users and also for login users, the get route for fetching blogs, the post route for posting blogs, delete route for deleting blogs.

Steps of code implementation

Step 1: Project setup

creating package.json: First create a project folder in the preferred location on the computer, open the terminal from the folder and run the command npm init -y.This initializes our node application & makes a package.json file.

installing dependencies: navigate to the project root directory in the terminal and type d following commands.

npm install express bcrypt body-parser cors dotenv express-rate-limit helmet joi jsonwebtoken mongoose passport passport-jwt passport-local

create server file: create an index.js and app.js file in the root directory to be used for creating an instance of the express module and const app for serving the API.

app.js file

const express = require("express");
const app = express();

app.get("/", (req,res) => {
    res.send("Hello world!")
})

module.exports = app;

index.js file

const app = require("./app")
require("dotenv").config();

const PORT = process.env.PORT || 3030

app.listen(PORT, () => {
    console.log('Listening on port, ', PORT)
})

create a dotenv, .env file in the project root directory and update it with the below code.

PORT=3030
MONGODB_URI=mongodb+srv://yourname:yourpassword@cluster0.yy9cqke.mongodb.net/serverName?retryWrites=true&w=majority
SECRET_KEY=yoursecret

Fetching data to app.js: the package body-parser helps to handle input data from the users. the app.js file can be updated as shown below.

const express = require("express");
const app = express();
const bodyParser = require("body-parser");

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

app.get("/", (req,res) => {
    res.send("Hello world!")
})

module.exports = app;

connecting to the database: for connecting to the MongoDB database, a package mongoose that has already been installed will be used, create a file db.js the project root directory and update both the file and index.js.

db.js

const mongoose = require("mongoose")

function connectTodb(){
    mongoose.connect("mongodb://localhost:27017/blogApi")

    mongoose.connection.on("connected",() => {
        console.log("connected to db succesfully")
    })

    mongoose.connection.on("error",() => {
        console.log("failed to connect to db")
    })
}

module.exports = { connectTodb }

index.js

const app = require("./app")
const { connectTodb } = require("./db");
require("dotenv").config();

const PORT = process.env.PORT || 3030

// connect to database
connectTodb();

app.listen(PORT, () => {
    console.log('Listening on port, ', PORT)
})

create a schema for storing user details and blogs with their model: create a folder in the project root directory named models.

creating user schema: in the models' directory, create a file name user.js and update it with the following code.

const mongoose = require('mongoose');
const bcrypt = require('bcrypt');

const Schema = mongoose.Schema;

const UserSchema = new Schema({
    firstname: String,
    lastname: String,
    email: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true,
        min: [6,"your password should be six letters long"]
    },
    posts: [
        {
          type: Schema.Types.ObjectId,
          ref: 'Post',
          required: true
        }
      ]
},{timestamps: true});

UserSchema.pre(
    'save',
    async function (next) {
        const user = this
        if (!user.isModified('password')) return next()
        const hash = await bcrypt.hash(user.password, 10);

        user.password = hash;
        next();
    }
);

UserSchema.methods.ValidatePassword = async function(password){
    const user = this;
    const compare = await bcrypt.compare(password, user.password);

    return compare;
}

module.exports = mongoose.model("User",UserSchema)

creating blog schema: also in the models' directory create a file post.js and update it to the below code.

const mongoose = require("mongoose");

const Schema = mongoose.Schema;

const PostSchema = new Schema(
  {
    authorName: {
      type: String,
      required: true
    },
    title: {
      type: String,
      required: true,
      unique: true,
    },
    description: {
      type: String,
    },
    state: {
      type: String,
      default: "draft",
      enum: ["draft", "published"],
    },
    read_count: {
      type: Number,
      default: 0,
    },
    reading_time: {
      type: String,
    },
    tags: {
      type: String,
    },
    body: {
      type: String,
      required: true,
    },
    author: {
      type: Schema.Types.ObjectId,
      ref: "User",
      required: true,
    },
  },
  { timestamps: true }
);
module.exports = mongoose.model("Post", PostSchema)