Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
November 14, 2020 08:10 am GMT

Building APIs Using Express.JS

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

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 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-servercd blog-server
Enter fullscreen mode Exit fullscreen mode
  • Create package.json file
npm init -y
Enter fullscreen mode Exit fullscreen mode
  • Create index.js file (entry file)
// index.jsconst PORT = 3000;console.log(`A node.js server that runs on ${PORT}`);
Enter fullscreen mode Exit fullscreen mode
  • Run the application
node index.js
Enter fullscreen mode Exit fullscreen mode

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 nodemonnpm install --save express cors body-parser morgan mongoose
Enter fullscreen mode Exit fullscreen mode
  • Import packages using require inside index.js file.
const express = require("express");const cors = require("cors");const bodyParser = require("body-parser");const morgan = require("morgan");const mongoose = require("mongoose");
Enter fullscreen mode Exit fullscreen mode

Database

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
mongoose.connect("mongodb://localhost:27017/blog");
Enter fullscreen mode Exit fullscreen mode
  • 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.
const postSchema = new mongoose.Schema(   {      title: { type: String, required: true },      body: { type: String, required: true },   },   { timestamps: true });
Enter fullscreen mode Exit fullscreen mode

MVC Like Application

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.
const Post = mongoose.model("post", postSchema);
Enter fullscreen mode Exit fullscreen mode

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
const postService = {   find: () => Post.find({}),   save: async (postData) => {      const post = new Post({ ...postData });      await post.save();      return post;   },};
Enter fullscreen mode Exit fullscreen mode

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
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);      }   },};
Enter fullscreen mode Exit fullscreen mode

Express Application

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
const app = express();MiddlewaresMiddlewares are functions executed before or after the controller actions.app.use(cors());app.use(morgan("tiny"));app.use(bodyParser.json());
Enter fullscreen mode Exit fullscreen mode

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
const router = express.Router();router.get("/posts", postController.find);router.post("/posts", postController.save);app.use("/api", router);
Enter fullscreen mode Exit fullscreen mode

Complete Example

I have included a complete express server example.

Conclusion

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.


Original Link: https://dev.to/bewarusman/building-apis-using-express-js-4cfb

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To