JavaScript is a very versatile programming language, it can be used for front-end, backend, and even Android developments, but I am here to talk about how I used it to build an API.
To write backend codes in JavaScript, you need ample knowledge of Node.js and Express.js to make your programming experience easier.
How It Works
Now, to the blog API; I'll be talking about the flow of the project and explaining step by step my thought process throughout the project.
A blog API is an API that takes requests either from a verified user or not verified one and provides a response, usually a blog or blogs, according to the user and the request. This API allows a user to register or log in, and it provides the user with a token, which can be used to make requests to protected or unprotected routes. A verified/registered user can choose to:
Get all available blogs
Get a blog
Get their blog
Create a new blog
Update their blog
Delete their blog.
Here is the flow of the blog, a user can choose to register or not however if they choose to not register, they can only make requests for blogs created by others and view a selected blog but if they choose to register they get a token that allows them to view, create, update and even delete their blogs plus the additional requests the non-verified user gets.
Some Codes And Algorithms Behind The Flow
We'll be coding, and bringing that idea to life using Node/Express.js and MongoDB.
The first thing we need to do is set up our MongoDB connection and listen/start the server once that is successful.
MongoDB's connection:
const mongoose = require('mongoose')
// database connection
module.exports = function connectDB (app){
const dbURI = process.env.MONGO_URL;
const PORT = process.env.PORT
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true, dbName:"BlogApp" })
.then((result) => app.listen(PORT, ()=>{
console.log(`App running at PORT: ${PORT} and MongoDB Server started`)
}))
.catch((err) => console.log(err));
}
Starting up the server:
const app = require('./app')
const connectDB = require('./config/db')
//database connection
connectDB(app)
We'll be following the MVC(Models-Views-Controllers) architectural pattern because it makes the flow easier and faster to complete.
After starting up the server, we make sure to install important middleware only, because we don't want our API taking up unnecessary space.
const express = require('express')
const passport = require('passport')
const rateLimit = require('express-rate-limit')
const helmet = require('helmet')
const app = express()
//dotenv
require('dotenv').config()
//Rate Limiting
const limiter = rateLimit({
windowMs: 0.5 * 60 * 1000,
max: 4,
standardHeaders: true,
legacyHeaders: false,
})
//security
app.use(helmet())
//MiddleWares
app.use(express.json());
//initialize passport
require('./config/passport')
app.use(passport.initialize());
module.exports = app
Once, the important middlewares are set up, we can now work on the models. The user model requires:
Name
Email
Password (hashed before saving to the database)
while the blog model requires:
Title
Description
Author
Author's ID
State (Published or Draft)
Read count
Tags
and The blog body
After all of that has been set up, we proceed to set up the routes and controllers because we won't be setting up views for this project. In the App.js file, we create a middleware for the routers and create a router's folder because we'll be having two routes. The /users routes will be handling all the creation and assigning of token logic, while the /blog routes will be handling the blog CRUD (create read update and delete) logic.
Setting up the /users' routes
The /users routes have only two acceptable routes, which are the /signup and the /login routes. The signup route accepts an email, a unique one, first name, last name, password, and confirm password as the body of the requests which are validated through Joi before sending a request, and it gets a response indicating the user has been created and a JWT token to access protected routes. While the login route takes the email, password, and confirm password as the body, and it verifies if the user is available in the database before sending back a token and a confirmation message.
Setting up the /blog routes
The /blog routes have the full CRUD functionality, and they are protected. The /blog route has:
A Get All Blog route which allows users, logged in or not, to see all available blogs on the API
A Get Blog route allows users, logged in or not, to see a selected blog and this increases the read count of the blog.
A Get My Blog route which allows logged-in users to see their blog only, and it can be filtered using whatever value they want to (as long as the value exists in the model)
A Post Blog route allows logged-in users to create a new blog, which will automatically be in a draft state until they decide it's time to update it.
A Patch Blog route allows blog owners to update the title, body, tags, description, or state of their blog.
A Delete Blog route allows blog owners to delete their preferred blog.