How to create a RESTful Blog API using Node.js

Devin Bandara
7 min readOct 30, 2021

Introduction

This application will be built using node.js, express.js, and mongoose. The goal of this app is to create a backend API that a frontend client could use to create, read, update and delete posts on a blog post application. To start off with, I will give some details about API’s and REST.

Application Programing Interfaces (API’s) allow frontend clients, such as a web browser, to communicate with a database in certain ways. Many popular web applications have their own API’s that you have worked with previously if you have some front-end development experience. Here are some examples of popular API’s to get started with if you have never worked with an API before:

Feel free to experiment with those or see if another web app you use has a well documented API. I encourage people to work with an API in the front end before they begin to build an API from scratch on the back end. This way you will get an idea of what data should look like when the client and server are communicating with each other.

What is REST

REST stands for Representational State Transfer. An interface needs to have 6 constraints to be RESTful:

  • Client & Server
  • Stateless
  • Cacheable
  • Uniform Interface
  • Layered System
  • Code on demand

Client & Server

Having a client and a server separates data storage concerns and improves the portability of the interface.

Stateless

Each request from the client to the server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client.

Cacheable

Cache constraints require that the data within a response to a request be implicitly or explicitly labeled as cacheable or non-cacheable. If a response is cacheable, then a client cache is given the right to reuse that response data for later, equivalent requests.

Uniform Interface

By applying the software engineering principle of generality to the component interface, the overall system architecture is simplified and the visibility of interactions is improved. In order to obtain a uniform interface, multiple architectural constraints are needed to guide the behavior of components. REST is defined by four interface constraints: identification of resources; manipulation of resources through representations; self-descriptive messages; and, hypermedia as the engine of application state.

Layered System

The layered system style allows an architecture to be composed of hierarchical layers by constraining component behavior such that each component cannot “see” beyond the immediate layer with which they are interacting.

Code on Demand (Optional)

REST allows client functionality to be extended by downloading and executing code in the form of applets or scripts. This simplifies clients by reducing the number of features required to be pre-implemented.

For more information about REST checkout this link.

Matos, Arturo, et al. “REST API Tutorial.” — Learn to Create Timeless RESTful APIs., restfulapi.net/

CRUD

Another requirement of a RESTful application is having CRUD functionality. CRUD stands for Create, Read, Update and Delete. Your app must be able to do all of these things with the data it is given.

Creating Our App

First let’s start with the creating the environment. I’m going to assume you have some experience creating apps using Node. If you don’t, you can install node on your machine here. It’s a pretty straightforward install.

We’re going to be using Express to make our app. We can do this by installing a package called express-generator. Open your terminal and type

$ npm install -g express-generator

The -g installs this package globally throughout your machine. Next, cd into the folder you want to create your new application. Let’s call it blog-app for now.

$ express blog-app

This will create your express application with the name specified.

$ cd blog-app
$ npm install
$ npm start

Here we cd into the project folder and install the dependencies listed in the app. Once the dependencies finish installing, you can start the app. To stop the server at any time press Control-C

npm may ask you to do fix some vulnerabilities after the npm install command. To fix this simply type npm audit fix

Let’s also take this time to install nodemon. Nodemon is a package that allows us to automatically restart our server when we make changes to our app.

$ npm install -g nodemon

Now to start our app instead of using nodemon . It won’t show anything right now because we haven’t set up our server yet. You can delete the “bin” folder in your project. Also open your package.json file and make sure that it says

"scripts": {   "start": "node server.js"}

This script tells the app where to look first. Now we can get started on the server code. Create a file in the project directory called server.js and copy-paste the code below

This creates a server on your local machine and gives it a get endpoint that displays the message “Hello world”. Nice! Now we’re on our way to meeting all the requirements of our RESTful app. Before we go any further creating more endpoints for our app we should create a model for the data that will reside in our database.

Building the database

For this specific tutorial I will be using MongoDB and Mongoose. MongoDB is a NoSQL database meaning that all the documents do not have to have the same property fields. You can work directly with MongoDB but in this case I prefer to use Mongoose which is a Object Document Modeling layer. It allows us to create schemas which will come in very handy.

Before we can actually build out our database, we have to create an empty one and connect it to our app. There are two main ways to do this. You can create a database on your local machine (your computer) and it can only be accessed by you. This is useful when you want to quickly build out a prototype, but if you want to build an app that other people can use, you want to store your database somewhere accessible. This is where mLab comes in. mLab will allow you to store your database on their servers which are powered by AWS. Go ahead and sign up and choose the free version. If you run out of space you can always upgrade. After you sign up, create a new database.

Choose Amazon as your cloud provider. For the plan type pick the free plan for now. Next, it will ask you to pick a location. Pick one that is closer to the main users of your application to lower ping times. After that you will name your database. Let’s just call ours blog-app. Go into your new blog-app database and in the “users” tab you’ll want to create a new database user. Save those user credentials somewhere secure if you don’t want other people to gain access to this database.

Next we will create a .env file to point our app to our database. In your config.js make sure there’s something that looks like this.

exports.PORT = process.env.PORT || 8080;exports.DATABASE_URL = process.env.DATABASE_URL || 'mongodb://localhost/todo-app';

After that create a file named .env in this file we will put our environmental variables. Copy the code you see in mLab that is listed as the URI

DATABASE_URL="mongodb://<dbuser>:<dbpassword>@ds335957.mlab.com:35957/blog-app"

You will want to change <dbuser> and <dbpassword> to the user credentials you saved earlier. Make sure you have the correct numbers in your link. They should match the URI on mLab. After you paste that code into your .env file we can go ahead and connect our database. The reason your user credentials are safe in your .env file is because only you can see what’s inside of it and it does not get pushed to github.

If you check your terminal, it will have an error saying Cannot finde module 'mongoose'. This is because we have to install mongoose. Make sure you are in your blog-app directory on terminal and then type

$ npm install mongoose

Now, if you check your package.json file, you should see mongoose in your dependencies. Next, create a file called models.js and inside that file paste this:

In that code we require mongoose, which we have already installed and then create a schema. You can learn more about schema’s here but they are used by mongoose to create a template for our data. Inside our schema we just have title and message. This is fine for now but we will want to add some more properties after we ensure that our database is working. We also add a serialize method to our post schema. Basically, the serialize method formats the data that will be returned to the client.

Now go back to your server.js file and add const mongoose = require("mongoose"); on line 3 just like we did in our models.js file.

Next thing we’re going to do is the final step for connecting our database. Below, you can see there is an if function with the condition (require.main === module). When a file is run by node, it sets require.main as its module so if we know that it is true, we can start our program.

mongoose.connect() is where we place our database URL that we imported on line 6 from our config.js file. (The information for our config.js file actually comes from our .env file)

You can see we created an app.get() function that finds all the posts in our database. We then pass the serialize method we created in our model.js file

models.js

connecting the app to the database

mongod

robo 3T

Endpoints

Part 2

Modularization

Routing

Part 3

Frontend

Deployment

--

--

Devin Bandara

CEO & Founder @ Nirvana Labs - Enlightening Blockchain Infrastructure