API Development Using Angular and ExpressJS

Nandan Pandey
7 min readMar 20, 2023
source

In this article we shall discuss different types of API requests and how to implement them using Express.js and Postman

So let’s start. The topics covered in this article are as follows:

i) API Definition and Methods

ii) Get Request

iii) PUT Request

iv) POST Request

v) DELETE Request

API Definition and Methods:

It’s an application programming interface that means it receives data from one program source, processes it and returns it to the same or other program source.

For better understanding we can see an example say user wants to see his/her profile then he clicks on some button say View Profile then what happens is his some unique id is passed from the UI (user interface) to the backend so that it can fetch user information from the database and then his details information is shown in the UI. Now what ever thing does all this process ( from transferring unique id to fetch data) is called API.

Their are 4 different types of API requests basically CRUD operations. CRUD means Create, Read, Update and Delete. To perform these CRUD operations their different different API Methods.

To Perform Create Operation we use POST method.

To Perform Read Operation We use GET method.

To Perform Update Operation we use PUT method.

To Perform Delete Operation we use DELETE method.

Now let’s see each one by one in detail and how to implement them in Express.js (In other articles we shall also discuss how to implement them using Django and Flask)

GET Request:

Get request is used to fetch the details from backend. We send a get request from frontend (UI, Angular) to backend (ExpressJS) that fetches data from database using some query (eg. SQL) and then returns back that fetched data as a json to UI and then it is displayed in UI.

Now let’s see how to send a get request from frontend using Angular:

In View component (view.component.ts): When view component is loaded then ngOnInit() lifecycle method is called that calls a method defined in the Service file.

import { Component, OnInit } from '@angular/core';
import { ProfileService } from '../profile.service';
@Component({
selector: 'app-view',
templateUrl: './view.component.html',
styleUrls: ['./view.component.css']
})
export class ViewComponent implements OnInit {

profileDetails : any = [];

constructor(private profileService: ProfileService) { }

ngOnInit(): void {
this.getProfileById();
}

getProfileById(id:any){
this.profileService.getProfileById(id).subscribe(
data =>{
this.profileDetails = data;
)
}

}

profile.service.ts: Here we call GET method of HTTP to get the details from backend.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';


@Injectable({
providedIn: 'root'
})

export class ProfileService {
constructor(private http: HttpClient) { }
getProfileById(id:any){
return this.http.get('http://localhost:3000/api/v1/profiles/' + id);
}
}

In Backend (ExpressJS) there is a file called routes.js that defines all the API routes.

routes.js

const express = require('express')
const router = express.Router()

const profileController = require('../controller/controller');

router.get('/:id', profileController.findById);

module.exports = router

This file contains a controller file that fetches data from database. Here we have used MySQL as database:

controller.js

'use strict';

const { response } = require('express');
const Profile = require('../model/model');

exports.findById = function(req, res) {
Profile.findById(req.params.id, function(err, profile) {
if (err)
res.status(202).send(err);
res.status(203).json(profile);
});
};

Now let’s see the model file (model.js).

'use strict';

var sqlConn = require('../../configs/mysql_config');

//Profile object create
var Profile = function(profile){
this.first_name = profile.first_name;
this.last_name = profile.last_name;
this.email = profile.email;
this.mobile = profile.mobile;
};

Profile.findById = function (id, result) {
sqlConn.query("Select * from profiles where id = ? ", id, function (err, res) {
if(err) {
console.log("error: ", err);
result(err, null);
}

else{
result(null, res);
}
});
};


module.exports= Profile;

POST Request:

Post request is used to create a new record in database. We send a post request (that is basically create button often) from frontend (UI, Angular) to backend (ExpressJS) that creates a new record in database table using some query (eg. SQL) and then returns back a success response as a json if successfully created else error response as designed in backend to UI and then that response is displayed in UI in a customized way.

Now let’s see how to send a post request from frontend using Angular:

In Create component (create.component.ts): When c create component is loaded then ngOnInit() lifecycle method is called that calls a method defined in the Service file.

import { Component, OnInit } from '@angular/core';
import { FormControl, Validators, FormGroup } from '@angular/forms';
import { ProfileService } from '../profile.service';

@Component({
selector: 'app-create',
templateUrl: './create.component.html',
styleUrls: ['./create.component.css']
})
export class CreateComponent implements OnInit {

constructor(private profileService: ProfileService) { }

profile_data = { 'first_name':'name_of_person',
'last_name': 'last_name_of_person',
'email': 'email_of_person',
'mobile': 'mobile_of_person',

}

ngOnInit(): void {
}

addProfile(){
this.profileService.addProfile(profile_data).subscribe(
data=>{
this.res = data;
if(this.res['error']){
alert(this.res['message'])
}
else{
alert(this.res['message'])
}
})
}
}

profile.service.ts: Here we call GET method of HTTP to get the details from backend.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable({
providedIn: 'root'
})
export class ProfileService {

constructor(private http: HttpClient) { }

addProfile(data:any){
return this.http.post('http://localhost:3000/api/v1/profiles/', data);
}
}

routes.js

const express = require('express')
const router = express.Router()

const profileController = require('../controller/controller');

router.post('/', profileController.create);

module.exports = router

This file contains a controller file that create new record in database.

controller.js

'use strict';

const { response } = require('express');
const Profile = require('../model/model');

exports.create = function(req, res) {
const newProfileObj = new Profile(req.body);
Profile.create(newProfileObj, function(err, profile) {
if (err)
res.status(206).json({error:true,message:"Error during creation of New Profile!"});
res.status(207).json({error:false,message:"Profile created successfully!",data:profile});
});
}

Now let’s see the model file (model.js).

'use strict';

var sqlConn = require('../../configs/mysql_config');
//Profile object create
var Profile = function(profile){
this.first_name = profille.first_name;
this.last_name = profile.last_name;
this.email = profile.email;
this.mobile = profile.mobile;
};

Profile.create = function (newProfile, result) {
sqlConn.query("INSERT INTO profiles set ?", newProfile, function (err, res) {
if(err) {
console.log("error: ", err);
result(err, null);
}
else{
console.log(res.insertId);
result(null, res.insertId);
}
});
};

module.exports= Profile;

PUT Request:

Put request is used to update the details. We send a put request from frontend (UI, Angular) to backend (ExpressJS) that updates data in database using some query (eg. SQL) and then returns back a success response if succeeded else error response as configured.

Now let’s see how to send a put request from frontend using Angular:

In edit component (edit.component.ts): When edit component is loaded then ngOnInit() lifecycle method is called that calls a method defined in the Service file.

import { Component, OnInit } from '@angular/core';
import { ProfileService } from '../profile.service';
import { ActivatedRoute } from '@angular/router';

@Component({
selector: 'app-view',
templateUrl: './edit.component.html',
styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {

profile_data = { 'first_name':'edit_name_of_person',
'last_name': 'edit_last_name_of_person',
'email': 'edit_email_of_person',
'mobile': 'edit_mobile_of_person',

}

constructor(private profileService: ProfileService, , private actRoute: ActivatedRoute) { }

ngOnInit(): void {
this.actRoute.paramMap.subscribe(params => {
this.id = params.get('id');
});

this.editProfile(this.id);
}

editProfile(){
this.profileService.editProfile(this.id, profile_data).subscribe(
data =>
{
this.res = data;
alert(this.res['message'])
})
}
}

profile.service.ts: Here we call PUT method of HTTP to get the details from backend.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ProfileService {
constructor(private http: HttpClient) { }
editProfile(id:any, data:any){
return this.http.put("http://localhost:3000/api/v1/profiles/" + id , data);
}

}

In Backend (ExpressJS) there is a file called routes.js that defines all the API routes.

routes.js

const express = require('express')
const router = express.Router()

const profileController = require('../controller/controller');
router.put('/:id', profileController.update);

module.exports = router

This file contains a controller file that updates data in database.

controller.js

'use strict';

const { response } = require('express');
const Profile = require('../model/model');

exports.update = function(req, res) {
var newProfileObj = new Profile(req.body);
Profile.update(req.params.id,newProfileObj , function(err, profile) {
if (err)
res.status(208).json({ error:true, message: 'Error occured during update of profile' });
res.status(209).json({ error:false, message: 'Profile successfully updated' });
});
};

Now let’s see the model file (model.js).

'use strict';

var sqlConn = require('../../configs/mysql_config');

var Profile = function(profile){
this.first_name = profille.first_name;
this.last_name = profile.last_name;
this.email = profile.email;
this.mobile = profile.mobile;
};

Profile.update = function(id, profile, result){
sqlConn.query("UPDATE profiles SET first_name=?,last_name=?,email=?,mobile=? WHERE id = ?", [profile.first_name,profile.last_name,profile.email,profile.mobile, id], function (err, res) {
if(err) {
console.log("error: ", err);
result(err, null);
}

else{
result(null, res);
}
});
};

module.exports= Profile;

DELETE Request:

Delete request is used to delete the record. We send a delete request from frontend (UI, Angular) to backend (ExpressJS) that deletes data from database using some query (eg. SQL).

Now let’s see how to send a delete request from frontend using Angular:

In delete component (delete.component.ts): When delete component is loaded then ngOnInit() lifecycle method is called that calls a method defined in the Service file.

import { Component, OnInit } from '@angular/core';
import { ProfileService } from '../profile.service';
@Component({
selector: 'app-view',
templateUrl: './delete.component.html',
styleUrls: ['./delete.component.css']
})
export class DeleteComponent implements OnInit {

profileDetails : any = [];
constructor(private profileService: ProfileService) { }

ngOnInit(): void {
}

deleteProfile(id:any){
this.profileService.deleteProfile(id).subscribe(
data=>{
this.res= data;
alert(this.res['message'])
})
}
}

profile.service.ts: Here we call DELETE method of HTTP to get the details from backend.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable({
providedIn: 'root'
})
export class ProfileService {

constructor(private http: HttpClient) { }

deleteProfile(id:any)
{
return this.http.delete('http://localhost:3000/api/v1/profiles/' + id);
}
}

In Backend (ExpressJS) there is a file called routes.js that defines all the API routes.

routes.js

const express = require('express')
const router = express.Router()

const profileController = require('../controller/controller');
router.delete('/:id', profileController.delete);
module.exports = router

This file contains a controller file that deletes record from database.

controller.js

'use strict';

const { response } = require('express');
const Profile = require('../model/model');

exports.delete = function(req, res) {
Profile.delete( req.params.id, function(err, profile) {
if (err)
res.status(210).json({ error:true, message: 'Error occured during deletion' });
res.status(211).json({ error:false, message: 'profile successfully deleted' });
});
};

Now let’s see the model file (model.js).

'use strict';

var sqlConn = require('../../configs/mysql_config');

var Profile = function(profile){
this.first_name = profille.first_name;
this.last_name = profile.last_name;
this.email = profile.email;
this.mobile = profile.mobile;
};

Profile.delete = function(id, result){
sqlConn.query("DELETE FROM profiles WHERE id = ?", [id], function (err, res) {
if(err) {
console.log("error: ", err);
result(err, null);
}

else{
result(null, res);
}
});
};

module.exports= Profile;
That's it for now. Here we saw how to implement different types of API methods using Angular and Express.Later We shall discuss how to implement APIs using Flask and Django. Also will discuss how to implement Swagger for a proper API documentation.Till then Happy Coding!!!

--

--