Author avatar

Gaurav Singhal

Understanding the Basics of HTTP

Gaurav Singhal

  • Jul 10, 2019
  • 14 Min read
  • 63 Views
  • Jul 10, 2019
  • 14 Min read
  • 63 Views
Front End Web Developer
Angular

Introduction

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.

How Does HTTP Works

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:

  • The browser (client) sends an HTTP request to the web.
  • The web server receives the request.
  • The server runs an application to process the request.
  • The server returns an HTTP response (as an output) to the browser.
  • The browser receives the response.
  • You can see the data that you want in the browser.

Getting Started

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.

1
npm install -g @angular/cli
shell

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.

Jumping to the Code

I am assuming that you now have Angular 7 setup, so let's jump into a simple example code.

Step 1: Start a New Project

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.

1
ng new HTTP tutorial
shell

This will create a tutorial directory with the following contents:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
HTTP tutorial
├── node_module               -- Installed Angular packages available in the project
└── src                       -- Contains the main code files.
    ├── app folder            -- Contains the files for app components
    ├── app.component.css     -- Cascading style sheets code for app component.
    ├── app.component.html    -- The HTML file related to the app component
    ├── app.component.spec.ts -- Unit testing file related to app component.
    ├── app.component.ts      -- Write view logic behind the component.
    └── app.module.ts         -- Includes all the dependencies for the website.
├── package.json              -- npm configuration file include packages version
├── package-lock.json         -- Auto-generated and modified file.
├── angular.json              -- Configuration file related to your angular application
├── .gitignore                -- File is related to the source control git.
├── .editorconfig             -- Maintain consistency in code editors to organize.
├── assets folder             -- Placeholder for resource files.
├── environments folder       -- Hold the environment configuration constants
├── browserlist               -- Adjusts the CSS to support a list of defined browsers.
├── favicon.ico               -- Small icon that appears next to the browser tab
├── index.html                -- Entry file holds the high-level container application.
├── karma.config.js           -- Config file for the Karma Test Runner
├── main.ts                   -- The main ts file that will first run.
├── polyfills.ts              -- Used to cover whatever feature missing from browser.
├── styles.css                -- Global CSS file which is used by an application.
├── tests.ts                  -- Use to traverse all the unit tests in the application
├── tsconfig.json             -- Typescript compiler configuration file.
├── tsconfig.app.json         -- Override the tsconfig.json file with app configurations.
├── tsconfig.spec.json        -- Override the tsconfig.json file with app unit test configurations.
docs

Step 2: Creating Our First Angular Application for Handle HTTP

Setting up the HttpClient: This is the first step to import HttpClientModule in src/app/app.module.ts.

1
2
3
4
5
6
7
8
9
import { HttpClientModule } from '@angular/common/http';
@NgModule({
    declarations: [
        AppComponent
    ],
imports: [BrowserModule,HttpClientModule],
bootstrap: [AppComponent]
})
export class AppModule { }
typescript

Create one class model: Use the command ng generate class class_name. I have named class name as employee.

1
ng generate class employee
shell

After a class is generated, you have to add objects:

1
2
3
4
5
6
export class Employee {
    id: number;
    employee_name: string;
    employee_salary:number;
    employee_age:number;
}
typescript

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.

1
ng generate service apicall
shell

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.

1
2
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Employee } from './employee';
typescript

In the constructor:

1
constructor(private httpClient: HttpClient) {}
typescript

To run in Angular, you can use the following command:

1
ng serve
shell

If you want to run in an open browser directly, use below command:

1
ng serve --open
shell

Step 3: Our First HTTP Request

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:

1
2
3
4
public nextPage: string = "";
public getEmployes(url?: string){
    return this.httpClient.get<Employee[]>(`http://dummy.restapiexample.com/api/v1/employees`);
}
typescript

In app.component.ts:

1
2
3
4
5
6
getEmployeeList(){
    this.apiService.getEmployes().subscribe((res)=>{ this.apiService.getEmployes(this.apiService.nextPage).subscribe((data:Employee[]) => {
        console.log(data);
        });
    });
}
typescript

In app.component.html:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Salary</th>
            <th>Age</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let emp of employees">
            <td>{{emp.employee_name}}</td>
            <td>{{emp.employee_salary}}</td>
            <td>{{emp.employee_age}}</td>
            <td >
                <button (click)="deleteEmployeeData(emp.id)">Delete</button>
            </td>
        </tr>
    </tbody>
</table>
html

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
3
4
5
6
7
8
9
10
11
12
13
14
[{
    "id":"81164",
    "employee_name":"XT4KT3OOPY",
    "employee_salary":"14137",
    "employee_age":"12",
    "profile_image":""
},
{
    "id":"81166",
    "employee_name":"2X4V49Z4GC",
    "employee_salary":"32387",
    "employee_age":"71",
    "profile_image":""
}]
json

GET Record by ID:

Follow the below code for getting a single record of the Employee.

In apicall.service.ts:

1
2
3
public getEmployeeById(id: number){
    return this.httpClient.get(`http://dummy.restapiexample.com/api/v1/employee/${id}`);
}
typescript

In app.component.ts:

1
2
3
4
5
getEmployee(id:number){
    this.apiService.getEmployeeById(id).subscribe((res:Employee[])=>{
      console.log(res);
    });
}
typescript

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
3
4
5
6
7
{
    "id":"81164",
    "employee_name":"XT4KT3OOPY",
    "employee_salary":"14137",
    "employee_age":"12",
    "profile_image":""
}
json

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:

1
2
3
public createEmployee(employee: any){
    return this.httpClient.post(`http://dummy.restapiexample.com/api/v1/create`,employee);
}
typescript

In app.component.ts:

1
2
3
4
5
createEmployeeData(){
    this.apiService.createEmployee(this.empPost).subscribe((res)=>{
        console.log("Created a employee");
    });
}
typescript

In app.component.html:

1
2
3
4
5
6
7
8
9
<form>
<input placeholder="Enter Employee Name" [(ngModel)]="empPost.name"/>
<br/>
<input placeholder="Enter Employee Salary"[(ngModel)]="empPost.salary">
<br/>
<input placeholder="Enter Employee Age" [(ngModel)]="empPost.age"/>
<br/>
<button type="submit" (click)="createEmployeeData()">Save</button>
</form>
html

From the above code, your request and response are given below:

Requested URL And Data:

1
2
Url: http://dummy.restapiexample.com/api/v1/create
Data: {"name":"abcd","salary":"123","age":"23"}
json

Server Response:

1
2
3
4
5
6
{
    "name":"abcd",
    "salary":"123",
    "age":"23",
    "id":"91614"
}
json

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:

1
2
3
public updateEmployee(employee: any){
    return this.httpClient.put(`http://dummy.restapiexample.com/api/v1/update/${employee.id}`,employee);
}
typescript

In app.component.ts:

1
2
3
4
5
updateEmployeeData(){
    this.apiService.updateEmployee(this.empPost).subscribe((res)=>{
        console.log("Updated the employee");
    });
}
typescript

In app.component.html:

1
2
3
4
5
6
7
8
9
<form>
<input placeholder="Enter Employee Name" [(ngModel)]="empPost.name"/>
<br/>
<input placeholder="Enter Employee Salary"[(ngModel)]="empPost.salary">
<br/>
<input placeholder="Enter Employee Age" [(ngModel)]="empPost.age"/>
<br/>
<button type="submit" (click)="updateEmployeeData()">Update</button>
</form>
html

From the above code, your request and response are given below:

Requested URL And Data:

1
2
Url: http://dummy.restapiexample.com/api/v1/update/91614
Data: {"name":"abcde","salary":"20000","age":"23"}
json

Server Response:

1
2
3
4
5
6
{
    "name":"abcde",
    "salary":"20000",
    "age":"23",
    "id":"91614"
}
json

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:

1
2
3
public deleteEmployee(id: number){
    return this.httpClient.delete(`http://dummy.restapiexample.com/api/v1/delete/${id}`);
}
typescript

In app.component.ts:

1
2
3
4
5
deleteEmployeeData(id:number){
    this.apiService.deleteEmployee(id).subscribe((res)=>{
        console.log("Deleted a employee");
    });
}
typescript

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"}}
json

Conclusion

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:

  • Get all the records of the employees.
  • Get a single record using the id of the employee.
  • Created the new records.
  • Updated the records of the employee.
  • Delete the employee records.

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.

0