Building APIs Using Express.JS
Tags: node, javascript, express, api
Published: 2020-11-14 08:10:34

## Summary
In this post, I will show you how to build a blog web API in Node.JS. This tutorial uses Express.JS for handling HTTP requests and Mongodb for storing data.

## Table Of Contents
* [Introduction](#chapter-1)
* [Setup](#chapter-2)
* [Database](#chapter-3)
* [MVC Structure](#chapter-4)
* [Express Application](#chapter-5)
* [Complete Example](#chapter-6)
* [Conclusion](#chapter-7)

## Introduction <a name="chapter-1"></a>
Node.JS is a platform used for building server side applications using Javascript. With Node.JS, developers are able to build backend APIs in minutes. It has a great community and a huge set of packages. These packages help the developers for building great applications. Developers does not require to build everything from scratch. We mainly focus on two packages. First is Express.JS, which is one of the most used packages by developers to build web APIs. Second is mongoose, which is used to simplify the communication between Node.JS and MongoDB.

#### Requirements
* Basic Javascript Knowledge
* Node.JS 10.0.0 or higher
* NPM 4.6.1 or higher
* Mongodb 4.2.1 or higher
* VS-Code or any other editor

## Setup <a name="chapter-2"></a>
A typical Node.JS application has a root directory which contains at least two files package.json (holds metadata about the application and required npm packages), and index.js file (a javascript entry file).

* Create the directory of the project
```
mkdir blog-server
cd blog-server
```
* Create package.json file
```
npm init -y
```
* Create index.js file (entry file)
```javascript
// index.js
const PORT = 3000;
console.log(`A node.js server that runs on ${PORT}`);
```
* Run the application
```
node index.js
```

#### Packages
Our express.js web application requires these packages.
* express: routing and middleware web framework
* cors: enables CORS (cross-origin resource sharing)
* body-parser: parses json body into javascript object
* morgan: log http requests, important for seeing the request
* mongoose: mongodb ORM
* nodemon: eases development by restarting the server on any change

NOTE: nodemon is used as a dev-dependency because it is required only during the development time.


* Install packages from NPM.
```
npm install --save-dev nodemon
npm install --save express cors body-parser morgan mongoose
```

* Import packages using require inside index.js file.
```javascript
const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const morgan = require("morgan");
const mongoose = require("mongoose");
```

## Database <a name="chapter-3"></a>
As mentioned above, we are using Mongodb for storing application related information. We use mongoose as object mapper between Mongodb and node.js application models.

* Connect to mongodb
```javascript
mongoose.connect("mongodb://localhost:27017/blog");
```

* Create mongoose schema to define the structure of the document that is read from or write to Mongodb.
Create a schema named postSchema to define the structure of posts, which it has title and body.
```javascript
const postSchema = new mongoose.Schema(
   {
      title: { type: String, required: true },
      body: { type: String, required: true },
   },
   { timestamps: true }
);
```

### MVC Like Application <a name="chapter-4"></a>
An MVC app is structured into three layers [models, views, controllers]. Sometimes, extra layers are added to MVC such as DAL, Services, Repositories.
In this example, the app is divided into three layers [models → services →controllers]. Usually, each layer exists in a directory.
#### Models
Models represent domain specific data. The model is based on postSchema defined above.
* create a Post model.
```javascript
const Post = mongoose.model("post", postSchema);
```
#### Services
Service layer is an additional layer in MVC that mediates communication between a Controller and a Model. This layer adds more abstractions and ease of testability.
Create a postService entity which exposes two services:
1. find: to query all post data
2. save: to save a post
```javascript
const postService = {
   
   find: () => Post.find({}),
   
   save: async (postData) => {
      const post = new Post({ ...postData });
      await post.save();
      return post;
   },
};
```
#### Controllers
Controllers as the name implies, controls the incoming request, catches errors and sends back a response to the client.
Create a postController which it has two actions:
1. find: handles GET /api/posts
2. save: handles POST /api/posts
```javascript
const postController = {
   
  find: async (req, res, next) => {
      try {
         const posts = await postService.find({ ...req.query });
         res.json(posts);
      } catch (error) {
         error.msg = "failed to retrieve posts";
         next(error);
      }
   },
   
   save: async (req, res, next) => {
      try {
         const post = await postService.save(req.body);
         res.json(post);
      } catch (error) {
         error.msg = "failed to create post";
         next(error);
      }
   },
};
```

## Express Application  <a name="chapter-5"></a>
Express is a routing and middleware web framework that has minimal functionality of its own: An Express application is essentially a series of middleware function calls.
* Create an express application
```javascript
const app = express();
Middlewares
Middlewares are functions executed before or after the controller actions.
app.use(cors());
app.use(morgan("tiny"));
app.use(bodyParser.json());
```
#### Express Router
The express router route the request to a specific action in the controller.
Define two routes based on Express Router to handle
1. GET /api/posts
2. POST /api/posts
```javascript
const router = express.Router();
router.get("/posts", postController.find);
router.post("/posts", postController.save);
app.use("/api", router);
```

## Complete Example <a name="chapter-6"></a>
I have included a complete express server example.
{% gist https://gist.github.com/bewarusman/ad7eee262f67ae1159a154f2a57d880d %}

## Conclusion <a name="chapter-7"></a>
You have learnt in detail, how to create an express server and connect to mongodb for storing data. You have exposed some APIs. In this tutorial I have written all code in one file for simplicity. You can visit this repository for the complete example.