We are living in a world where we are surrounded by information, and the internet is the main interface between us and that information. We use websites, web apps, mobile apps, etc. and, within seconds, we can obtain information very easily. Simply, we are using Google typing "http://www.google.com" and with a single click we get Google page. Have you ever thought about how it works? Do you want to know? If you’re here, I can only assume the answer is, “Yes,” and we are going to describe it.
HTTP stands for Hypertext Transfer Protocol
Web applications are work by exchanging information. ”Exchanging information, how is it possible?” Whenever you surf the web, your browser sends an HTTP request messages for HTML pages, images, scripts, and style sheets. Web servers handle these requests by returning response messages that contain the requested resource. HTTP is the Bridge for Communication; it enables the exchange of information over the internet. HTTP is the bridge, but for communication, we the WWW (World Wide Web) which is responsible for the connection between client and server.
In this guide, we will learn about HTTP and how to exchange information or data between the client and server.
All the communication between the client and server happens via request and response. HTTP has HTTP Requests and HTTP Responses to communicate with.
This is what happens under the hood:
Before getting started with the guide, I will let you know we are using Angular7 to handle HTTP. So, make sure you have Node.js in your system; if not, install it from here.
The next thing you need to do is install Angular; let's install it by npm.
1npm install -g @angular/cli
Note: It is recommended to have an IDE; some of the best choices are Visual Studio Code or JetBrains WebStorm.
Angular is a JavaScript framework which allows you to be able to create reactive, single-page applications. This is a leading front-end development framework which is regularly updated by Angular. Angular 7 is entirely based on components. It is beneficial to understand HTTP, so we are using an Angular application to understand HTTP.
I am assuming that you now have Angular 7 setup, so let's jump into a simple example code.
Since Angular is a framework, we need to follow some standards of the framework. To create a new project in Angular, use the command ng new project_name. I have named my project HTTP tutorial.
1ng new HTTP tutorial
This will create a tutorial directory with the following contents:
1HTTP tutorial
2├── node_module -- Installed Angular packages available in the project
3└── src -- Contains the main code files.
4 ├── app folder -- Contains the files for app components
5 ├── app.component.css -- Cascading style sheets code for app component.
6 ├── app.component.html -- The HTML file related to the app component
7 ├── app.component.spec.ts -- Unit testing file related to app component.
8 ├── app.component.ts -- Write view logic behind the component.
9 └── app.module.ts -- Includes all the dependencies for the website.
10├── package.json -- npm configuration file include packages version
11├── package-lock.json -- Auto-generated and modified file.
12├── angular.json -- Configuration file related to your angular application
13├── .gitignore -- File is related to the source control git.
14├── .editorconfig -- Maintain consistency in code editors to organize.
15├── assets folder -- Placeholder for resource files.
16├── environments folder -- Hold the environment configuration constants
17├── browserlist -- Adjusts the CSS to support a list of defined browsers.
18├── favicon.ico -- Small icon that appears next to the browser tab
19├── index.html -- Entry file holds the high-level container application.
20├── karma.config.js -- Config file for the Karma Test Runner
21├── main.ts -- The main ts file that will first run.
22├── polyfills.ts -- Used to cover whatever feature missing from browser.
23├── styles.css -- Global CSS file which is used by an application.
24├── tests.ts -- Use to traverse all the unit tests in the application
25├── tsconfig.json -- Typescript compiler configuration file.
26├── tsconfig.app.json -- Override the tsconfig.json file with app configurations.
27├── tsconfig.spec.json -- Override the tsconfig.json file with app unit test configurations.
Setting up the HttpClient: This is the first step to import HttpClientModule in src/app/app.module.ts.
1import { HttpClientModule } from '@angular/common/http';
2@NgModule({
3 declarations: [
4 AppComponent
5 ],
6imports: [BrowserModule,HttpClientModule],
7bootstrap: [AppComponent]
8})
9export class AppModule { }
Create one class model: Use the command ng generate class class_name. I have named class name as employee.
1ng generate class employee
After a class is generated, you have to add objects:
1export class Employee {
2 id: number;
3 employee_name: string;
4 employee_salary:number;
5 employee_age:number;
6}
For HTTP URL calls, we need a service file in Angular. Use the command ng generate service service_name. I have named class name as apicall.
1ng generate service apicall
Why services?
Components shouldn't fetch or save data directly, and they certainly shouldn't knowingly present fake data. They should focus on presenting data and delegate data access to a service. Here we are using apicall.service.ts.
After you’ve generated apicall.service.ts, import the HTTP client and initialize it in the constructor as given below.
1import { HttpClient, HttpHeaders } from '@angular/common/http';
2import { Employee } from './employee';
In the constructor:
1constructor(private httpClient: HttpClient) {}
To run in Angular, you can use the following command:
1ng serve
If you want to run in an open browser directly, use below command:
1ng serve --open
HTTP defines a set of request methods to indicate the desired action to be performed for a given resource.
Lets see all the methods for making requests and its implementations one by one.
GET Method: The GET method requests a representation of the specified resource. Requests using GET should only retrieve data.
Follow the below code for getting all records of the Employee.
In apicall.service.ts:
1public nextPage: string = "";
2public getEmployes(url?: string){
3 return this.httpClient.get<Employee[]>(`http://dummy.restapiexample.com/api/v1/employees`);
4}
In app.component.ts:
1getEmployeeList(){
2 this.apiService.getEmployes().subscribe((res)=>{ this.apiService.getEmployes(this.apiService.nextPage).subscribe((data:Employee[]) => {
3 console.log(data);
4 });
5 });
6}
In app.component.html:
1<table>
2 <thead>
3 <tr>
4 <th>Name</th>
5 <th>Salary</th>
6 <th>Age</th>
7 </tr>
8 </thead>
9 <tbody>
10 <tr *ngFor="let emp of employees">
11 <td>{{emp.employee_name}}</td>
12 <td>{{emp.employee_salary}}</td>
13 <td>{{emp.employee_age}}</td>
14 <td >
15 <button (click)="deleteEmployeeData(emp.id)">Delete</button>
16 </td>
17 </tr>
18 </tbody>
19</table>
From the above code, your request and response are given below:
Requested URL:
Url: http://dummy.restapiexample.com/api/v1/employees
Server Response:
1[{
2 "id":"81164",
3 "employee_name":"XT4KT3OOPY",
4 "employee_salary":"14137",
5 "employee_age":"12",
6 "profile_image":""
7},
8{
9 "id":"81166",
10 "employee_name":"2X4V49Z4GC",
11 "employee_salary":"32387",
12 "employee_age":"71",
13 "profile_image":""
14}]
GET Record by ID:
Follow the below code for getting a single record of the Employee.
In apicall.service.ts:
1public getEmployeeById(id: number){
2 return this.httpClient.get(`http://dummy.restapiexample.com/api/v1/employee/${id}`);
3}
In app.component.ts:
1getEmployee(id:number){
2 this.apiService.getEmployeeById(id).subscribe((res:Employee[])=>{
3 console.log(res);
4 });
5}
From the above code, your request and response are given below:
Requested URL:
Url: http://dummy.restapiexample.com/api/v1/employee/81164
Server Response:
1{
2 "id":"81164",
3 "employee_name":"XT4KT3OOPY",
4 "employee_salary":"14137",
5 "employee_age":"12",
6 "profile_image":""
7}
POST Method: The POST method is used to submit an entity to the specified resource, often causing a change in the state or side-effects on the server.
Follow the below code for creating a new Employee.
In apicall.service.ts:
1public createEmployee(employee: any){
2 return this.httpClient.post(`http://dummy.restapiexample.com/api/v1/create`,employee);
3}
In app.component.ts:
1createEmployeeData(){
2 this.apiService.createEmployee(this.empPost).subscribe((res)=>{
3 console.log("Created a employee");
4 });
5}
In app.component.html:
1<form>
2<input placeholder="Enter Employee Name" [(ngModel)]="empPost.name"/>
3<br/>
4<input placeholder="Enter Employee Salary"[(ngModel)]="empPost.salary">
5<br/>
6<input placeholder="Enter Employee Age" [(ngModel)]="empPost.age"/>
7<br/>
8<button type="submit" (click)="createEmployeeData()">Save</button>
9</form>
From the above code, your request and response are given below:
Requested URL And Data:
1Url: http://dummy.restapiexample.com/api/v1/create
2Data: {"name":"abcd","salary":"123","age":"23"}
Server Response:
1{
2 "name":"abcd",
3 "salary":"123",
4 "age":"23",
5 "id":"91614"
6}
PUT Method: The PUT method replaces all current representations of the target resource with the request payload.
Follow the below code for updating an Employee record.
In apicall.service.ts:
1public updateEmployee(employee: any){
2 return this.httpClient.put(`http://dummy.restapiexample.com/api/v1/update/${employee.id}`,employee);
3}
In app.component.ts:
1updateEmployeeData(){
2 this.apiService.updateEmployee(this.empPost).subscribe((res)=>{
3 console.log("Updated the employee");
4 });
5}
In app.component.html:
1<form>
2<input placeholder="Enter Employee Name" [(ngModel)]="empPost.name"/>
3<br/>
4<input placeholder="Enter Employee Salary"[(ngModel)]="empPost.salary">
5<br/>
6<input placeholder="Enter Employee Age" [(ngModel)]="empPost.age"/>
7<br/>
8<button type="submit" (click)="updateEmployeeData()">Update</button>
9</form>
From the above code, your request and response are given below:
Requested URL And Data:
1Url: http://dummy.restapiexample.com/api/v1/update/91614
2Data: {"name":"abcde","salary":"20000","age":"23"}
Server Response:
1{
2 "name":"abcde",
3 "salary":"20000",
4 "age":"23",
5 "id":"91614"
6}
DELETE Method: To Delete data from the server, we are using the Delete method.
Follow the below code for deleting the Employee record.
In apicall.service.ts:
1public deleteEmployee(id: number){
2 return this.httpClient.delete(`http://dummy.restapiexample.com/api/v1/delete/${id}`);
3}
In app.component.ts:
1deleteEmployeeData(id:number){
2 this.apiService.deleteEmployee(id).subscribe((res)=>{
3 console.log("Deleted a employee");
4 });
5}
From the above code, your request and response are given below:
Requested URL:
Url: http://dummy.restapiexample.com/api/v1/delete/91626
Server Response:
1{"success":{"text":"successfully! deleted Records"}}
So, you have successfully built an Angular application where we give complete details about HTTP and how it works on our request to get a response from the server.
Here are some of the ways that you can expand your code for learning purposes, if you are curious:
Now you should understand how HTTP is used for communication. Mobile apps are very famous these days and keeping all data on phone does not makes sense as it changes every second; and hence these apps uses HTTP for fetching and sending data over the Internet.
For checking how requests and responses act on any HTTP URL you are working with, you can use Postman.