Building RESTful APIs with Node.js and Angular: A Comprehensive Guide

Any web application needs a mechanism to connect with its backend server, and the rest APIs are that way. So, in this blog, we’ll go into great detail on what rest APIs are and how to make them easily.

What is REST API?

REST in restful API stands for “Representational State Transfer” and API for “Application Programming Interface”. It is an architecture that employs HTTP requests to store and access data from databases utilizing servers.

Following are the 5 important HTTP methods used by REST API

  1. GET Method – The Get method is used to obtain any data or record from a database.
  2. POST Method – The Post method is used to save any data or record in a database.
  3. PUT Method – The Put method is used to update any existing data on the server.
  4. PATCH Method – The Patch method is also used for updating a record in a database, the only difference between the two is that the Patch method updates only a portion of the data rather than the entire record.
  5. DELETE Method – The Delete method is used for deleting any record in a database.

This is how the whole architecture would look like:

REST API Architecture
REST API Architecture

Essential Back-end Basics

Before we start building the REST API, I’d like to go over certain back-end concepts you should be aware of.

🔸 Request – A request is anything the client sends to the server; it can be a get request, a post request, a put request, a patch request, or a delete request.

🔸 Response – When a client submits a request to a server, the server processes that specific request and responds by sending the client a response.

🔸 Request Body – The request body is the data that is sent by the client when it submits a request to the server.

🔸 Middleware – Middleware is a broad topic in and of itself, but in simple terms, middleware is used to handle incoming requests before they reach the controller.

Let’s begin by developing REST APIs using Node.js

We’ll build a manager-employee CRUD rest API that allows the manager to add employees, see specific employees, edit employees, and delete employees using REST APIs.

The tech stack that we’ll need to build the CRUD rest API is listed below:

Note: Instead of the front end, we will put a lot of effort into developing REST APIs.

Step 1️⃣ – Project Setup and Package Installation

Create one folder and open your preferred code editor.

 1.1 Run the following command

npm init -y

1.2 Install the following packages

npm install express mongoose dotenv cors

Description of the packages installed

  1. Express: Express is a strong library that will assist us in building our server.
  2. Mongoose: Mongoose will assist us in developing a database schema, this package also includes built-in types and validations.
  3. Dotenv: Dotenv package will help us in creating environment variables for different environments like development and production.
  4. Cors: To bypass the Cors error.

Step 2️⃣ – Creating an Express Server

2.1 Create one file index.js and paste the following code

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

dotenv.config();

const PORT = process.env.PORT || 8000;

app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});

1.2 Install nodemon package for automatic refresh

Npm install -d nodemon

-d flag will install nodemon package as a dev dependency.

2.3  Open the package.json file and write the following script in the “Scripts” section

"dev":"nodemon index.js"

2.4  Finally run the following command to start the server

Npm run dev

You will see the output as Server running on port 5000 or 8000.

Step 3️⃣ – Creating Environment File

Create .env file and paste the following code

PORT=5000
DB_URL="mongodb://localhost:27017/emp_crud"

Note: /emp_crud is our db name

Step 4️⃣ – Creating DB Schema and DB Connection

4.1 – Create one folder called config and inside the config folder create one file called dbConnection.js

4.2 – Open dbConnection.js file and paste the following code:

const mongoose = require("mongoose");
const dotenv = require("dotenv");
dotenv.config();

//DB uri
const uri = process.env.DB_URL;

mongoose.connect(uri, { useUnifiedTopology: true, useNewUrlParser: true });

const connection = mongoose.connection;

module.exports = connection;

Note: To access the environment variables in this case, we are utilizing the dotenv package.

4.3 – For db schema create one folder called models and inside the models folder create one file called empModels.js and paste the following code:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

let employee = new Schema({
name: {
type: String,
},
email: {
type: String,
},
gender: {
type: String,
},
salary: {
type: Number,
},
department: {
type: String,
},
});

module.exports = mongoose.model("employees", employee);

Step 5️⃣ – Creating Endpoints and Controllers

5.1 – Create one folder called modules and inside the modules folder create the employees folder.

Inside the employees folder create two more folders controllers and routes.

The folder structure would look something like this.

folder structure in building restful API

5.2 – Inside the controller folder create one file called empControllers.js and paste the following code:

The logic that will be invoked when a certain endpoint is requested is contained in the file empControllers.js.

Every endpoint we create has a specific controller attached to it that will handle the request and respond to the client.

It’s a recommended practice to place your business logic within a try-catch block for improved error handling because every controller you see is written inside one.

const empModel = require("../../../models/employee/empModels");

module.exports = {
addEmployee: async (req, res) => {
try {
const employee = await empModel.create(req.body);
await employee.save();
res.status(201).send({ message: "Employee added", success: true });
} catch (error) {
res.status(500).send({ message: "Internal server error", success: false });
}
},
getAllEmployees: async (req, res) => {
try {
const employees = await empModel.find({});
if (employees.length > 0) {
res.status(200).send({ data: employees, success: true });
} else {
res.status(200).json({ message: "user not found", success: true });
}
} catch (error) {
res.status(500).send({ message: "Internal server error", success: false });
}
},
updateEmployee: async (req, res) => {
try {
const resp = await empModel.updateOne({ _id: req.body.id },
{ ...req.body })
res.status(200).json({ message: "Update success", success: true });

} catch (error) {
res.status(500).send({ message: "Internal server error", success: false });
}
},
deleteEmployee: async (req, res) => {
try {
const employeExist = await empModel.findOne({ _id: req.body.id });
if (employeExist) {
const deleteEmp = await empModel.deleteMany({ _id: req.body.id });
if (deleteEmp["deletedCount"] >= 1) {
res.status(200).send({ message: "Delete success", success: true });
} else {
res.status(500).send({ message: "Something went wrong..!", success: false });
}
} else {
res.status(200).send({ message: "User not found", success: false });
}
} catch (error) {
res.status(500).send({ message: "Internal server error", success: false });
}
}
};

5.3 – Inside the routes, folder create one file called empRoutes.js and paste the following code:

const router = require("express").Router();
const empControllers = require("../controller/empControllers");

//Get employees
router.get("/getemployees", empControllers.getAllEmployees);

//Save employee
router.post("/save-employee", empControllers.addEmployee);

//Update employees
router.put("/update-employee", empControllers.updateEmployee);

//Delete employee
router.delete("/delete-employee", empControllers.deleteEmployee);

//Exporting routes
module.exports = router;

We are almost there, Now replace the following code in the index.js file.

const express = require("express");
const dotenv = require("dotenv");
const bodyParser = require("body-parser");
const empRoute = require("./modules/employees/routes/empRoutes");
const connection = require("./config/db/dbConnection");
const cors = require("cors");

const app = express();

//Global middlewares
app.use(bodyParser.json());
app.use(express.urlencoded({ extended: true }));
app.use(
cors({
origin: "*",
methods: ["GET", "POST", "PUT", "DELETE", "PATCH"],
})
);

dotenv.config();
const PORT = process.env.PORT || 8000;

//Checking DB connection here
connection.once("open", function () {
console.log("MongoDB database connection established successfully");
});

//setting employee routes
app.use("/api/emp", empRoute);

app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});

Now let’s integrate these APIs into an Angular application. Only the angular service will be covered in this section.

API Integration into Angular Application

Create one service in your application

Use the following command for creating an angular service application

Ng g s services/api

After this paste the following code

import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';
import { HttpClient } from '@angular/common/http';
import { empModel } from '../models';

@Injectable({
providedIn: 'root',
})
export class ApiService {
addEmployeeUrl = environment.baseUrl + '/save-employee';
getEmployeesUrl = environment.baseUrl + '/getemployees';
updateEmployeesUrl = environment.baseUrl + '/update-employee';
deleteEmployeesUrl = environment.baseUrl + '/delete-employee';
constructor(private http: HttpClient) {}

addEmployee(obj: empModel) {
return this.http.post(this.addEmployeeUrl, obj);
}

getAllEmployees() {
return this.http.get(this.getEmployeesUrl);
}

updateEmployee(obj: empModel) {
return this.http.put(this.updateEmployeesUrl, obj);
}

deleteEmployee(id: any) {
return this.http.delete(this.deleteEmployeesUrl, id);
}
}

Now, you can use any component to inject this service into and use the APIs.

coma

Conclusion

This project serves as a testament to the power and flexibility of REST APIs in modern application development. With the project setup and package installation steps covered, it is now up to developers to customize and enhance the API according to their specific requirements.

I hope you enjoyed reading this blog and learned a few new methods for creating RESTful APIs.

Keep Reading

Keep Reading

Struggling with EHR integration? Learn about next-gen solutions in our upcoming webinar on Mar 6, at 11 AM EST.

Register Now

Let's create something together!