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.
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
This is how the whole architecture would look like:
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.
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
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.
Create .env file and paste the following code
PORT=5000 DB_URL="mongodb://localhost:27017/emp_crud"
Note: /emp_crud is our db name
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);
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.
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.
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.
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.
How to Effectively Hire and Manage a Remote Team of Developers
The Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
Mindbowser has truly been foundational in my journey from concept to design and onto that final launch phase.
CEO, KickSnap
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork